ma1*_*w28 18 ruby class self instance class-method
我知道这self是实例方法中的实例.那么,self类方法中的类是什么?例如,以下是否会在Rails中工作?
class Post < ActiveRecord::Base
def self.cool_post
self.find_by_name("cool")
end
end
Run Code Online (Sandbox Code Playgroud)
Sté*_*hen 23
那是正确的.self在类方法中是类本身.(还有在类定义中,例如selfin def self.coolpost.)
您可以使用irb轻松测试这些花絮:
class Foo
def self.bar
puts self.inspect
end
end
Foo.bar # => Foo
Run Code Online (Sandbox Code Playgroud)
class Test
def self.who_is_self
p self
end
end
Test.who_is_self
Run Code Online (Sandbox Code Playgroud)
输出:
测试
现在,如果你想要一个特定于Rails的解决方案,它就叫做named_scopes:
class Post < ActiveRecord::Base
named_scope :cool, :conditions => { :name => 'cool' }
end
Run Code Online (Sandbox Code Playgroud)
像这样使用:
Post.cool
Run Code Online (Sandbox Code Playgroud)
已有很多答案,但这就是为什么自我是班级的原因:
点变为self点之前的任何内容.所以,当你foo.bar为bar-method 做的时候,self是foo.类方法没有区别.打电话时Post.cool_post,你会self改为Post.
这里需要注意的重要一点是,不是如何定义方法self,而是如何定义方法.这就是为什么这有效:
class Foo
def self.bar
self
end
end
class Baz < Foo
end
Baz.bar # => Baz
Run Code Online (Sandbox Code Playgroud)
或这个:
module Foo
def bar
self
end
end
class Baz
extend Foo
end
Baz.bar # => Baz
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11430 次 |
| 最近记录: |