<< operator in ruby

I'm new to ruby

I came across the following code in rails, but I don’t know how the "<<operator works and what it does in the code below

 def <<( rate ) r = Rating.new r.rate = rate r.rateable = proxy_owner ... ... end class << ActiveRecord::Base ... ... end 

Can someone explain to me?

Edit: here is the code https://github.com/azabaj/acts_as_rateable/blob/master/lib/acts_as_rateable.rb

0
source share
2 answers

def <<( rating ) : In your example, this is used to add a rating to the model with a variable speed. (For example, in actions_as_rateable.rb: 41 ), similar to adding something to a string ( str << "abc" ). Since it is inside the module, it will be included only for models that you declare as paid.

class << ClassName :

All methods inside this block will be static / class methods (see this blog post ). (In this case, all models will have Model.example_static_method methods.)

+3
source

Almost all operators in Ruby are actually instance methods called on the object that precedes them.

For << there are many different uses, depending on the type of object you are calling it on. For example, in an array, this works to push the given value to the end of the array.

This seems to apply to the Rails model object, so in this case I would say that this is a helper method called when adding a model object to model a collection of objects. For example, in this case you can add a rating to the product.

If you indicated the definition of the whole method and showed which class it is in, I could give a more specific answer.

+2
source

Source: https://habr.com/ru/post/1401718/


All Articles