Eval

Discussion in 'Ruby' started by John, Sep 9, 2003.

  1. John

    John Guest

    I am trying to create a class with attributes that are values
    retrieved from a database. E.g.

    class Item
    attr_accessor :color
    def initialize(color)
    @color = color
    end
    end

    z = Item.new("yellow")

    resultset = {"fruit" => "banana"}

    I'd like to now set an accessor for z.fruit and set the value to
    banana.

    Is there a define_attribute method like there's a define_method
    method?

    To put it succinctly, how can I create instance attributes after the
    instance has already been created? Here's my greenhorn attempt, but I
    wonder if I'm hurting performance by invoking eval or if there's a
    more accepted way to do it:

    def add_attribute(name, val)
    instance_eval <<-EOD
    def #{name}= (val)
    @#{name} = val
    end
    def #{name}
    @#{name}
    end
    @#{name} = "#{val}"
    EOD
    end

    z.add_attribute( resultset[0], resultset[1] )
    puts z.fruit #banana
     
    John, Sep 9, 2003
    #1
    1. Advertising

  2. John

    Dan Doel Guest

    Other ways if you can't use a struct for some reason.
    Method2 not recommended (unless you check if the accessor has been
    defined yourself).

    - Dan

    class Method1
    def add_attr(name, val)
    class << self
    self
    end.class_eval { attr_accessor name }
    send("#{name}=", val)
    end
    end

    class Method2
    def initialize
    @dict = Hash.new {nil}
    end

    def method_missing(sym, *args)
    str = sym.to_s
    /(.*)(=?)/ =~ str

    if $2.empty?
    @dict[$1.intern]
    else
    @dict[$1.intern] = args[0]
    end
    end

    def add_attr(name, val)
    @dict[name.intern] = val
    end
    end

    obj = Method1.new

    obj.add_attr("foo", "bar")

    obj2 = Method2.new
    obj2.add_attr("baz", "frob")

    p obj.foo

    p obj2.baz
    p obj2.any_undefined_method_name
     
    Dan Doel, Sep 9, 2003
    #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. Eric Newton
    Replies:
    3
    Views:
    9,416
    Brock Allen
    Apr 4, 2005
  2. DataBinder.Eval and Eval.

    , Jun 16, 2006, in forum: ASP .Net
    Replies:
    1
    Views:
    549
    Karl Seguin [MVP]
    Jun 16, 2006
  3. Alex van der Spek

    eval('07') works, eval('08') fails, why?

    Alex van der Spek, Jan 8, 2009, in forum: Python
    Replies:
    6
    Views:
    1,453
    Bruno Desthuilliers
    Jan 8, 2009
  4. Liang Wang
    Replies:
    8
    Views:
    134
    Ben Morrow
    Feb 2, 2008
  5. Marc Girod

    to eval or not to eval?

    Marc Girod, Apr 19, 2011, in forum: Perl Misc
    Replies:
    2
    Views:
    159
    Marc Girod
    Apr 19, 2011
Loading...

Share This Page