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 是模块 ActionController 中名为 Base
的类的新派生类。下一行会发生什么? 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"
关于ruby-on-rails - ruby 类中的语法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33276499/