Let's say I have the following classes:
class Foo
attr_accessor :name, :age
end
class Bar
def initialize(name)
@foo = Foo.new
@foo.name = name
end
end
I would like to define an accessor on Bar, which is just an alias of foo.name. Easy enough:
def name
@foo.name
end
def name=(value)
@foo.name = value
end
With just one property, this is simple enough. However, let's say Foo provides several properties that I want to open through Bar. Instead of defining each method manually, I want to do something like this, although I know that the syntax is incorrect:
[:name, :age].each do |method|
def method
@foo.method
end
def method=(value)
@foo.method = value
end
end
So ... What is the correct way to define such methods?
source
share