开发者

Rails: when to use self

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

Here is the code of a method that I would like to fully understand. If it is possible I would like to have an alternative to this code so it would make things more clear.

def self.for(faceb开发者_Python百科ook_id)
  User.create_by_facebook_id(facebook_id)
end


self refers to the current object.

Within a class, self is used to define a class-level method.

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

defines a class method for in class Foo. It is invoked:

Foo.for(facebook_id)

You can google for class methods to learn more.

It could be that a part of Rails or a plugin/gem is expecting that some classes will have a class method "for" More context would be helpful in this regard.

What the method is doing

As is common for class methods, it is creating an instance of a class. For example, the ActiveRecord class has a class method "create" which attempts to create an instance of the model class that has been stored in the database. Thus User.create will return an instance of the User class that has been stored in the database.

In your example code, it is calling a class method "create_by_facebook_id" that is provided by the User class in the application.

Looks like the "for" method is being used for information hiding since all it's doing is making another method call (to User.create_by_facebook)

Added:

By the way, the default return value from Ruby methods is the value of the last statement. So your example method will return the user instance newly created from the supplied facebook_id.


It looks to me like self.for is just an alias for creating a user for a facebook id. I think self.for should actually be:

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

That way it searches for the user with that facebook id, and if one isn't found, creates that record and returns it. Then, self.for means "return the user for this facebook id."


Short answer: self always refers to the current object. So within an instance method, self is the instance, within a class method, self is the class and within a class definition (like in your example), self is the class...

For more information on class methods and the code snippet you posted, see the answer by Larry K.


If that code is inside of a class named Foo, then the alternative could be:

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

self in this context is necessary if you have some generic class level methods that you want to be able to use across multiple classes. You add them to a Module using self. to scope them (as you don't know the name of the actual class that they are going to a part of), then include that module as part of your class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜