rails定义方法的不同方式



到目前为止,我已经研究Rails很长时间了。。。。所以如果有请随时纠正我

我看到在rails 中有两种定义方法的方法

  1. def method_name(param)
  2. def self.method_name(param)

区别(据我所知)是1主要用于控制器,而2用于模型。。。但有时我会碰到像1这样定义的模型中的方法。

你能向我解释一下这两种方法的主要区别吗?

数字1。这定义了一个instance method,可以在模型的实例中使用
第二。这定义了一个class method,并且只能由类本身使用
示例:

class Lol
  def instance_method
  end
  def self.class_method
  end
end
l = Lol.new
l.instance_method #=> This will work
l.class_method #=> This will give you an error
Lol.class_method #=> This will work

方法self.method_name定义类上的方法。基本上,在类定义中,把自我看作是指被定义的类。因此,当你说defself.method_name时,你就是在类本身上定义方法。

class Foo 
  def method_name(param)
     puts "Instance: #{param}"
  end
  def self.method_name(param)
     puts "Class: #{param}"
  end
end
> Foo.new.method_name("bar")
Instance: bar
> Foo.method_name("bar")
Class: bar

最新更新