ruby clases中的语法是什么?

可能是
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>'
西蒙妮·卡莱蒂(Simone Carletti)

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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Ruby的语法是什么?

来自分类Dev

::在Ruby语法中是什么意思?

来自分类Dev

Ruby中的->(){}是什么?

来自分类Dev

Ruby中的委托是什么?

来自分类Dev

Ruby中的`super`是什么?

来自分类Dev

Ruby中的$:是什么意思

来自分类Dev

=〜和/ \在Ruby中是什么意思?

来自分类Dev

在Ruby / Rails中,“ Rails”是什么?

来自分类Dev

$ /在Ruby中是什么意思?

来自分类Dev

“ || =“在Ruby中是什么意思?

来自分类Dev

Ruby on Rails中的“ _path”方法是什么?

来自分类Dev

Ruby中的“&:name”是什么意思

来自分类Dev

Ruby中eval的替代方法是什么?

来自分类Dev

Ruby模块中的“基础”是什么?

来自分类Dev

Ruby中的“ +”是什么意思?

来自分类Dev

$在Ruby中是什么意思?

来自分类Dev

$ /在Ruby中是什么意思?

来自分类Dev

Ruby中的奇怪语法

来自分类Dev

Ruby中的语法“ && =“

来自分类Dev

Ruby on Rails 上的#<..> 是什么?

来自分类Dev

Ruby on Rails中的可变语法

来自分类Dev

厨师食谱中的Ruby语法

来自分类Dev

这种Ruby语法是什么意思:如果self <Class :: Name?

来自分类Dev

Ruby版本语法,xxx-dev,preview,rc,最旧和最新的是什么?

来自分类Dev

Ruby中的单号和(&)符号是什么意思?

来自分类Dev

在Ruby中,逗号后跟等号是什么意思?

来自分类Dev

Ruby正则表达式中的“?-mix”是什么

来自分类Dev

在Ruby中,浮动范围的默认步骤是什么?

来自分类Dev

Ruby中基于机架的服务器是什么