Ruby on rails 在不实例化类的情况下调用ruby方法
如果我调用rails活动模型方法上的方法,如下所示:Ruby on rails 在不实例化类的情况下调用ruby方法,ruby-on-rails,ruby,instance-methods,class-method,Ruby On Rails,Ruby,Instance Methods,Class Method,如果我调用rails活动模型方法上的方法,如下所示: class Foo < ActiveRecord::Base end Foo.first class Foo
class Foo < ActiveRecord::Base
end
Foo.first
class Foo
我会找回第一条活动记录。我不必实例化这个类
但如果我创建自己的类并调用一个方法,我会得到一个异常:
class Person < ActiveRecord::Base
def greeting
'hello'
end
end
Person.greeting
#EXCEPTION: undefined method `greeting' for Person:Class
class-Person
我怎样才能解决这个问题 尝试类方法:
class Person < ActiveRecord::Base
def self.greeting
'hello'
end
end
class-Person
或其他语法:
class Person < ActiveRecord::Base
class << self
def greeting
'hello'
end
end
end
class-Personclass-Person
有几种方法。两个最重要的方法是:实例方法和类实例方法
Foo.first
是一个类实例方法。它在类实例上工作(Foo
,在本例中)。如果它在类中存储了一些数据,那么该数据将在整个程序中全局共享(因为只有一个类的名称为Foo(确切地说是::Foo
)
但是您的问候语
方法是一个实例方法,它需要对象实例。例如,如果您的问候语方法将使用人名,那么它必须是实例方法,以便能够使用实例数据(名称)。如果它不使用任何特定于实例的状态,并且您真的希望它是一个类实例方法,那么请使用self
“前缀”
class-Person
要执行静态方法,请尝试以下操作:
class MyModel
def self.do_something
puts "this is a static method"
end
end
MyModel.do_something # => "this is a static method"
MyModel::do_something # => "this is a static method"
类MyModel
做点什么
将“这是一个静态方法”
结束
结束
MyModel.do#u something#=>“这是一个静态方法”
MyModel::do#u something#=>“这是一个静态方法”
class-Person
这也行。我喜欢它,因为它很清楚它的作用;但是,当您决定重命名Person类时,它将导致错误 除了,你知道,ruby中没有静态方法:)仅供参考,你所拥有的几乎肯定不应该在模型中,而应该在视图或助手中
class Person < ActiveRecord::Base
def self.greeting
'hello'
end
end
class MyModel
def self.do_something
puts "this is a static method"
end
end
MyModel.do_something # => "this is a static method"
MyModel::do_something # => "this is a static method"
class Person < ActiveRecord::Base
def Person.greeting
'hello'
end
end