On Fri, Feb 15, 2013 at 7:36 PM, Jesse F. [email protected] wrote:
I want to associate information to instances of Form that FormItems can
use.
How do I associate the object of a container with the container? Or what
is a smart Ruby way (I know there are a lot of ways)?
So a FormItem belongs to one Form, and you want it to be able to read
things from it?
One way would be to pass the Form instance to the FormItems, either in
the constructor, if the Form is constructing the items, or in the code
that tells a Form that this item belongs to it.
First case:
class Form
def initialize
@items = []
@items << FormItem.new(:item, :init, :params, self)
[…] # other items
end
end
class FormItem
def initialize item, init, params, container
@container = container
[…] #rest of initialization
end
end
Note in the constructor of the Form, we are passing self to the form
items. Form items would be able then to call methods of form using
their instance variable @container.
Second way:
class Form
def initialize
@items = []
end
def add_item item
item.container = self
@items << item
end
end
class FormItem
attr_reader :container
def initialize item, init, params
[…] #rest of initialization
end
end
f = Form.new
item = FormItem.new :a, :b, :c
f.add_item item
Hope this gives you some ideas,
Jesus.