Rails: when to use self

I am developing a Rails application and want to understand when to use self.for.

Here is the method code that I would like to fully understand. If possible, I would like to have an alternative to this code so that it becomes more understandable.

def self.for(facebook_id)
  User.create_by_facebook_id(facebook_id)
end
+3
source share
4 answers

self refers to the current object.

Inside the class, self is used to define the class level method.

class Foo
  def self.for(facebook_id)
    User.create_by_facebook_id(facebook_id)
  end
end

defines the class method for the Foo class. Called:

Foo.for(facebook_id)

You can google for class methods to find out more.

It is possible that part of the Rails or plugin / gem expects some classes to have a class for method. More context would be helpful in this regard.

, . , ActiveRecord "create", , . , User.create User, .

"create_by_facebook_id", User .

, "for" , , , ( User.create_by_facebook)

:

, Ruby- . , , facebook_id.

+10

, self.for - facebook. , self.for :

def self.for(facebook_id)
  User.find_or_create_by_facebook_id(facebook_id)
end

, facebook, , . self.for " facebook".

0

: self . , self , self (, ) self ...

, , . .

0

Foo, :

def Foo.for(facebook_id)
  User.create_by_facebook_id(facebook_id)
end

selfin this context, it is necessary if you have common class-level methods that you want to use for several classes. You add them in Modulewith self.to cover them (since you do not know the name of the actual class in which they belong), then include this module as part of your class.

0
source

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


All Articles