[英]Ruby: calling methods on init
I switched to Ruby from PHP, and have yet to understand a curious Ruby class behavior where methods are executed outside of the class method definitions (see example below). 我从PHP切换到Ruby,但尚未了解一种奇怪的Ruby类行为,其中的方法是在类方法定义之外执行的(请参见下面的示例)。 In PHP, when we wanted to execute anything on class init, we would put it in the constructor method. 在PHP中,当我们想在类init上执行任何操作时,可以将其放入构造方法中。
Ruby example (Rails): Ruby示例(Rails):
class Comment < ActiveRecord::Base
belongs_to :post, :counter_cache => true
end
Am I correct in understanding that belongs_to
will be executed on instantiation? 我理解在实例化时将执行belongs_to
是否正确? And is belongs_to
a class method inherited from ActiveRecord? 并belongs_to
一个从ActiveRecord继承的类方法吗?
Thanks! 谢谢!
In Ruby, everything is executable code. 在Ruby中, 一切都是可执行代码。 Or, to put it another way: everything is a script. 或者,换句话说: 一切都是脚本。 There is no such thing as a "class declaration" or something like that. 没有“类声明”之类的东西。
Any code that sits in a file, without being inside anything else like a method body, a class body, a module body or a block body, is executed when that file is load
ed (or require
d or require_relative
d). load
文件(或require
d或require_relative
d)时,将执行文件中位于任何文件中,而不位于方法主体,类主体,模块主体或块主体之内的任何代码。 This is called a script body . 这称为脚本主体 。
Any code that sits inside a class or module body is executed when that class or module is created. 创建该类或模块时,将执行位于该类或模块主体内的任何代码。 (This is the case you are referring to.) (您指的是这种情况。)
The boring part: any code that sits inside a method body is executed when that method is called, or more precisely, when that method is invoked in response to receiving a message with the same name as the method. 无聊的部分:位于方法主体内的任何代码都在调用该方法时执行,或更确切地说,在响应于接收到与该方法同名的消息而调用该方法时执行。 (Duh.) (杜)。
Any code that sits inside a block body is executed when that block is yield
ed to. yield
该块时,将执行位于该块体内的任何代码。
Since a class definition is just a script, this means that it can contain any sort of code you want, including method calls: 由于类定义只是脚本,因此这意味着它可以包含所需的任何类型的代码,包括方法调用:
class Foo
attr_accessor :bar # Yes, attr_accessor is just a method like any other
private # I *bet* you didn't know *that* was a method, too, did you?
end
or conditionals: 或条件:
class Bar
if blah # e.g. check if the OS is Windows
def foo
# one way
end
else
def foo
# a different way
end
end
end
Yes, it's a class method from ActiveRecord. 是的,这是ActiveRecord的类方法。 The method will execute when the class itself is created, not when an instance of it is created. 该方法将在创建类本身时执行,而不是在创建其实例时执行。
Yes , that's correct. 是的 , 没错 。 See also this question . 另请参阅此问题 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.