"class <<" 是什么意思?自我"在 Rails 中是什么意思? [英] what does "class << self" mean in Rails?

查看:43
本文介绍了"class <<" 是什么意思?自我"在 Rails 中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
class <<Ruby 中的自我习语
有人可以解释一下班级吗<<<自我对我?

我想知道 class <<self 语句在模型类中是什么意思?以及它内部的语句与外部的语句有何不同.例如:

I would like to know what does class << self statement mean in a model class? And how does the statement inside it differ from those outside from it. For example:

class Post < ActiveRecord::Base

  class << self
     def search(q)
          # search from DB
     end
  end
   def search2(qq)
         # search from DB
   end
end

class <<self 是什么意思?

search(q)search2(qq) 方法有什么区别?

What are the differences between method search(q) and search2(qq) ?

推荐答案

同上

class Post < ActiveRecord::Base

  def self.search(q)
    # Class Level Method
    # search from DB
  end

  def search2(qq)
    # Instance Level Method
    # search from DB
  end
end

类方法作用于类(例如 Post),实例方法作用于该类的实例(例如 Post.new)

Class methods work on the class (e.g. Post), instance methods works on instances of that class (e.g. Post.new)

有些人喜欢 类 <<自己;代码;end; 方式,因为它将所有类级别的方法保存在一个漂亮的块和一个地方.

Some people like the class << self; code; end; way because it keeps all class level methods in a nice block and in one place.

其他人喜欢在每个方法前加上 self. 以明确知道这是一个类方法而不是实例方法.这是风格和编码方式的问题.如果你把所有的类方法放在一个块中,比如 class <<self,而且这个块够长,class<< 行可能在您的编辑器视图之外,因此很难知道您在类实例块中.

Others like to prefix each method with self. to explicitly know that is a class method not an instance method. It's a matter of style and how you code. If you put all class methods in a block like class << self, and this block is long enough, the class << self line might be out of your editor view making it difficult to know that you are in the class instance block.

另一方面,在每个方法前面加上 self. 并将它们与实例方法混合也是一个坏主意,你在阅读代码时如何知道所有的类方法.

On the other hand, prefixing each method with self. and intermixing those with instance methods is also a bad idea, how do you know all the class methods while reading your code.

为自己的代码库选择一个您喜欢的习惯用法,但如果您从事开源项目或与他人合作编写代码,请使用他们的代码格式规则.

Pick an idiom which you prefer for your own code base but if you work on an open source project or you collaborate on someone else's code, use their code formatting rule.

这篇关于"class &lt;&lt;" 是什么意思?自我"在 Rails 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆