0
votes

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!

3
What are you expecting exactly from the bar method ? Should it only behave as a getter to an Array object ? - David
@David that's exactly right. What I want to achieve is like ActiveRecord has_many relations where you can do @project.line_items << LineItem.create(...) - Nik So
@Nik, @project.line_items << ... returns an Array, not @project. It'd be impossible for Foo.new.bar to return an array that can have << called on it and a Foo object simultaneously! - Daniel Vandersluis
Are you sure you only want to support << ? What would happen if someone performs @foo.bar.insert(position, 'Smile') ? - David
You know, that's a very good point. Although the position of this particular Array is thankfully not important, it does give sight to the unforseen possible future needs that might give trouble. - Nik So

3 Answers

2
votes
class Foo
   attr_reader :bar
   def initialize
     @bar = Array.new
     def @bar.<< arg
       self.push arg.id
     end
   end

end

class Bar
  attr_accessor :id
  def initialize id
    self.id = id
  end
end


f = Foo.new
bars = (1..5).map{|i| Bar.new i}

f.bar << bars[2]
f.bar << bars[4]

p f.bar  #=> [3, 5]
1
votes

Return an object that has the << method defined.

0
votes

Unless I'm misunderstanding what you're wanting, why not just make the bar method a getter for an internal array member?

class Foo
  attr_reader :bar

  def initialize
    @bar = []
  end
end

f = Foo.new
f.bar << 'abc'
# f.bar => ['abc']