Ruby on rails ruby类中的语法是什么?
错误:Ruby on rails ruby类中的语法是什么?,ruby-on-rails,ruby,Ruby On Rails,Ruby,错误: class Base def foo @name = "foo" end end class Der < Base foo def bar @dummy = "bar" end end expr1.rb:62:in`':未定义的局部变量或Der:Class的方法'foo'(NameError) from expr1.rb:61:in`' 它的继承。在您的子类中,您可以使用从parrent类继承的所有方法。 首先,您可以在类实例上调用方法。 在
class Base
def foo
@name = "foo"
end
end
class Der < Base
foo
def bar
@dummy = "bar"
end
end
expr1.rb:62:in`':未定义的局部变量或Der:Class的方法'foo'(NameError)
from expr1.rb:61:in`'
它的继承。在您的子类中,您可以使用从parrent类继承的所有方法。
首先,您可以在类实例上调用方法。
在你的例子中,你可以这样做:
expr1.rb:62:in `<class:Der>': undefined local variable or method `foo' for Der:Class (NameError)
from expr1.rb:61:in `<main>'
base_object = Base.new
base_object.foo
der_object = Der.new
der_object.bar
class ApplicationController < ActionController::Base
但也要感谢遗传,你可以做这样的事情:
expr1.rb:62:in `<class:Der>': undefined local variable or method `foo' for Der:Class (NameError)
from expr1.rb:61:in `<main>'
base_object = Base.new
base_object.foo
der_object = Der.new
der_object.bar
class ApplicationController < ActionController::Base
下面是关于ruby继承的简单教程,并附有示例:
快乐编码 要创建类方法,可以执行以下任一操作
der_object.foo
类基
def self.foo
结束
结束
阶级基础
class是在ActionController::Base
中包含的一个模块中定义的类方法,当您从ActionController::Base
继承时,该类方法可供子类使用
Rails中的这种方法有时被称为“宏”,因为它们是启用某些特定功能的类方法(有时还使用元编程来定义额外的方法或助手)。实际上,术语“宏”是不正确的,因为Ruby没有宏。它们只是类方法
要记住的最重要的细节是,在类定义中使用它们时。这些方法在代码计算时运行,而不是在运行时运行
class Base
def self.foo
end
end
class Base
class << self
def foo
end
end
end
所以你说的是“类方法”——类方法是在类本身上定义的方法,而不是在类的实例上定义的方法。注意以下几点:
"foo class"
"bar"
#greet
是Greeter
类上的一个实例方法。但是,.new
是一个“类方法”——它是在类本身上调用的方法。试图在问候者
类上调用问候者
,将导致名称错误
:
class Greeter
def initialize(name)
@name = name
end
def greet
"hello, #{@name}"
end
end
Greeter.new("bob").greet # => "hello, bob"
因此,如果要定义此类“类方法”,必须使用以下语法之一:
Greeter.greet # ! NameError
这也适用于子类化:
class Greeter
greet "bob" # => "hello, bob"
end
类主机“你好,鲍勃”
结束
Rails就是这样提供这些方法的——它们在基类上定义类方法,最常见的是ActiveRecord::base
,然后您可以使用这些方法——解释诸如protect\u from\u forgery
protect\u from\u forgery是一个类方法:可以如下所示
class Host < Greeter
greet "bob" # => "hello, bob"
end
因此,它由应用程序控制器继承:
def protect_from_forgery(options = {})
self.forgery_protection_strategy = protection_method_class(options[:with] || :null_session)
self.request_forgery_protection_token ||= :authenticity_token
prepend_before_action :verify_authenticity_token, options
append_after_action :verify_same_origin_request
end
这些是rails方法,不是ruby。这就是你找不到他们的原因。它是@japed中的一个类方法。我如何创建这样的方法?什么时候执行?为什么我的示例不起作用?当然,正如我说的,您需要在类的实例上,在某些类对象上调用实例方法。要理解这种方法,我建议您阅读一些OOP教程。这个很好:
class Base
class << self
def foo
@name = "foo"
end
end
end
class Der < Base
foo #class method from Base
def bar
@dummy = "bar"
end
end
Der.foo.inspect