gorn
gorn

Reputation: 5340

how to add syntactic sugar to rails similar to collections

How one can add syntactic sugar similar to rails "add to collection" << operator, i.e.

@object.collection << item

I was trying to do

class Object
  def collection<<(item)
    ...
  end
end

but it does not work. Optionally I would like to define my own "operators" on attributes.

Note - i am aware hot to use def <<(value) but it works for the whole object not for its attribute.

Upvotes: 0

Views: 338

Answers (3)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

@object.collection << item

Let's take this apart.

  • @object - well, some object.
  • collection - when @object is sent this message it returns something.
  • << - this message is sent to the object that was returned from the collection message.
  • item - parameter to << message.

Example

class Foo
  def << val
    puts "someone pushed #{val} to me"
  end
end

class Bar
  def collection
    @foo ||= Foo.new
  end
end

b = Bar.new

b.collection << 'item'
# someone pushed item to me

By the way, these forms do the same thing and produce the same output.

b.collection << 'item'
b.send(:collection).send(:<<, 'item')
b.collection.<<('item')
b.collection.<< 'item'

Upvotes: 3

Gareth
Gareth

Reputation: 138042

This isn't possible based on how Ruby works. You will need your collection method to return an object which has your custom << method on it.

Upvotes: 1

davetron5000
davetron5000

Reputation: 24841

<< is a method of Array, so this works in plain Ruby:

def MyClass
  def initialize
    @collection = []
  end
  def collection
    @collection
  end
end

MyClass.new.collection << 'foo'

Upvotes: 0

Related Questions