class ApplicationController < ActionController::Base
protect_from_forgery #What is this syntax? When is this executed and how to create one?
end
class Comment < ActiveRecord::Base
belongs_to :post
attr_accessible :body, :commenter, :post
end
在第一种情况下,我了解ApplicationController是Base
在模块ActionController中调用的新的派生类。下一行会发生什么?是protect_from_forgery
在基类或模块的ActionController的方法?这叫什么?我在ruby类文档中找不到。我尝试在基类中创建一个方法,但出现如下错误。如何创建可在类中使用的特殊命令?
class Base
def foo
@name = "foo"
end
end
class Der < Base
foo
def bar
@dummy = "bar"
end
end
错误:
expr1.rb:62:in `<class:Der>': undefined local variable or method `foo' for Der:Class (NameError)
from expr1.rb:61:in `<main>'
protect_from_forgery
是在ActionController::Base
从中继承的子模块中包含的一个模块中定义的类方法,当您从中继承时,该方法可用于子类ActionController::Base
。
Rails中的这种方法有时称为“宏”,因为它们是启用某些特定功能的类方法(有时还使用元编程来定义额外的方法或辅助方法)。实际上,术语“宏”是不正确的,因为Ruby没有宏。它们不过是类方法。
要记住的最重要的细节是,在类定义中使用它们时。这些方法在代码评估而不是在运行时运行。
class Base
def foo_instance
p "foo instance"
end
def self.foo_class
p "foo class"
end
end
class Der < Base
foo_class
def bar
p "bar"
end
end
Der.new.bar
将产生
"foo class"
"bar"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句