Dynamic methods / accessors

(Frodo Larik) #1

Hi all,

I'm trying to setup some kind of dynamic method / accessor assignment to objects. But I don't want the other objects from the same class to know about "personal" methods. I'm just learning Ruby, so it could be I missed something.

For example:

class MyThing
    def create_method(method)
       # I found two things on internet which can acchieve this
       # self.class.class_eval { attr_accessor method }
       # AND
       # self.class.send(:define_method, method, &block)
       # but I'm not sure which is the best one to use, but I think
       # I prefer the attr_accessor, because that's the functionality
       # I need
    end
end

# Create first object
a = MyThing.new
a.create_method('box') # Adds a method box to a
a.box = 'something inside'

# The nicest thing would be if I could do something like this:
a.create_method('box','some_value'), so a.box is populated with 'some value'

# Create second object
b = MyThing.new

# I don't want the following to happen
b.box = 'something other'

I don't want the method 'box' be available to b, only to a

How can I achieve this?

I saw it was possible to achieve this with something like this:

class YourThing < MyThing
    # A placeholder class for the dynamic methods
end

but I don't know the name of the class on forehand, so if something like this is possible:

class #{i_want_this_class} < MyThing
    # A placeholder class for the dynamic methods
end

That would be nice.

Sincerely,

Frodo Larik

(ts) #2

# Create first object
a = MyThing.new
a.create_method('box','some_value'), so a.box is populated with 'some value'
# Create second object
b = MyThing.new

# I don't want the following to happen
b.box = 'something other'

moulon% cat b.rb
#!/usr/bin/ruby
class MyThing
   def create_method(meth, init)
      class << self; self end.send(:attr_accessor, meth)
      send("#{meth}=", init)
   end
end

a = MyThing.new
a.create_method('box','some_value')

p a, a.box

b = MyThing.new
p b
b.box = 'something other'
moulon%

moulon% ./b.rb
#<MyThing:0xb7d70958 @box="some_value">
"some_value"
#<MyThing:0xb7d70804>
./b.rb:16: undefined method `box=' for #<MyThing:0xb7d70804> (NoMethodError)
moulon%

Guy Decoux