Hello, I have a skeleton class:
class Foo
def bar
# returns some sort of array
end
end
but how can one add the 'writer' method to 'bar' so to enable the Array#push behavior?
Foo.new.bar<<['Smile']
_.bar #=> ['Smile']
EDITED: I should expand my question further. There are two classes. Foo, and Bar, much like the ActiveRecord has_many relation where Foo has_many Bars
But I am actually storing the ids of Bar inside a method of Foo. I name that method bar_ids
so @foo = Foo.new(:bar_ids => [1,2,3])
As you can imagine, if I ever want to look up what Bars belong to @foo, I have to actually do something like Bar.where(:id => @foo.bar_ids)
So I decided to make another method just named bar to do just that class Foo #... def bar Bar.where(:id => bar_ids) end end
That worked out. now I can do @foo.bar #=> all the bars belonging to @foo
Now I also want to have that kind of push method like ActiveRecord associations, just to cut out the "id" typing when associating another bar object to a foo object
Currently, this works: @foo.bar_ids << Bar.new.id @foo.save
But I want: @foo.bar << Bar.new #where the new bar's id will get pushed in the bar_ids method of @foo @foo.save
Thanks for all of your help, I really appreciate your thoughts on this!