我正在学习一些 Rspec 的东西,不小心将一些代码引入了我的模型类,我预计这会产生错误。但令我惊讶的是没有。
class Address < ActiveRecord::Base
attr_accessible :city, :country, :person_id, :street, :zip
validates_presence_of :city, :zip, :street
before_save :setDefaultCountry
# -- Beginning strange code --
if true
puts "Hey! I shouldn't be able to do this"
end
# -- End of strange code --
private
def setDefaultCountry
if self.country.blank?
self.country = "US"
end
end
end
这是 Rails 控制台输出:
Arman$ rails console
Loading development environment (Rails 3.2.3)
1.9.3p194 :001 > a = Address.new
Hey! I shouldn't be able to do this
=> #<Address id: nil, street: nil, city: nil, zip: nil, country: nil, person_id: nil, created_at: nil, updated_at: nil>
1.9.3p194 :002 >
为什么 ruby 不提示在类定义中添加了奇怪的代码?
最佳答案
因为 class
block 只是为代码的执行引入了一个新的上下文。 Ruby 是 Ruby,不是 C++——不要这样对待它。如果我们想在类定义期间执行一些代码,您认为我们为什么不能这样做?您可以在其中很好地执行代码 - 在此期间,self
将指向代表您的类的 Class
对象,而不是其类的任何实例。这为您提供了极大的灵 active ,并且是使 Ruby 猴子可修补的重要因素之一(从 Ruby 主义者的角度来看,这是一个加号,尽管许多其他人不赞成这种做法)。
关于ruby-on-rails - 为什么我可以将随机代码添加到我的 Ruby 类定义中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10631150/