ruby-on-rails - ruby 类中的语法是什么?

标签 ruby-on-rails ruby

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/

相关文章:

ruby-on-rails - Rails 中 has_one 和 belongs_to 的区别?

ruby - 在 ruby​​ 中迭代枚举

ruby-on-rails - 如何确保 Sidekiq 后台作业针对启动它们的同一数据库运行

ruby-on-rails - Rails 应用程序和聊天

ruby-on-rails - 强参数中嵌套对象中的Rails 4嵌套数组

ruby-on-rails - 为什么不显示验证错误消息?

ruby-on-rails - 使用 presigned_url 触发 S3 文件的下载

ruby-on-rails - 不确定为什么要在这里使用 Proc - 不是简单的东西

ruby-on-rails - 参数错误 : invalid radix -1

ruby-on-rails - 重构 LIst 排序方法的 Controller 代码