Magic method instantiation

Discussion in 'Ruby' started by Artūras Šlajus, Nov 5, 2006.

  1. I have this method in module:

    def text_field_tag(*args)
    args.push(nil) if args.length == 1

    args.push({}) if args.length == 2
    args.last['class'] ||= 'text_field_tag' if args.last.kind_of? Hash
    super(*args)
    end

    It works fine, the problem is that I need to define lots of these
    methods.

    I tried using:

    def class_extendor(*args)
    args.each do |arg|
    define_method(name) do |*args|
    args.push(nil) if args.length == 1

    args.push({}) if args.length == 2
    args.last['class'] ||= name if args.last.kind_of? Hash
    super(*args)
    end
    end
    end

    class_extendor "text_field_tag", "text_field_tag2"

    but it doesn't work (no wonders why...)

    Anyway, ideas how to implement that?

    --
    Posted via http://www.ruby-forum.com/.
    Artūras Šlajus, Nov 5, 2006
    #1
    1. Advertising

  2. > def class_extendor(*args)
    > args.each do |arg|
    > define_method(name) do |*args|
    > args.push(nil) if args.length =3D=3D 1
    >=20
    > args.push({}) if args.length =3D=3D 2
    > args.last['class'] ||=3D name if args.last.kind_of? Hash
    > super(*args)
    > end
    > end
    > end
    >=20
    > class_extendor "text_field_tag", "text_field_tag2"
    >=20
    > but it doesn't work (no wonders why...)


    I would guess because you're using the variable args twice - the fact
    that you've used it on the outside (as the parameter to your method)
    means that it has a wider scope. But without knowing what your expected
    output and actual output are, I can't be bothered trying to read your
    mind further.
    Daniel Sheppard, Nov 5, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Bengt Richter
    Replies:
    3
    Views:
    319
    Mike Meyer
    Nov 23, 2005
  2. Replies:
    1
    Views:
    571
    Salt_Peter
    Dec 25, 2006
  3. mathieu
    Replies:
    8
    Views:
    457
    Alf P. Steinbach
    Aug 6, 2009
  4. mathieu
    Replies:
    1
    Views:
    525
    mathieu
    Aug 6, 2009
  5. Giles Bowkett
    Replies:
    9
    Views:
    400
    Giles Bowkett
    Dec 17, 2007
Loading...

Share This Page