Tag: 类方法

在不实例化类的情况下调用ruby方法

如果我在rails活动模型方法上调用方法,如下所示: class Foo < ActiveRecord::Base end Foo.first 我会回到第一个活跃的记录。 我不必实例化该类。 但是如果我创建自己的类并调用方法,我会得到一个exception: class Person < ActiveRecord::Base def greeting 'hello' end end Person.greeting #EXCEPTION: undefined method `greeting' for Person:Class 我怎么能让这个问题消失呢?

如果没有这样定义,你怎么能在邮件程序上调用类方法呢?

在Rails中发送邮件时,通常可以这样做: UserMailer.password_reset(user).deliver 但是,如果我们查看UserMailer我们可以看到: def password_reset(user) # not self.password_reset # … end 请注意,方法名称不以self为前缀。 看一下,看起来你需要首先实例化对象,如下所示。 Rails如何做到这一点? UserMailer.new.password_reset(user).deliver

(在Ruby中)允许混合类方法访问类常量

我有一个定义了常量的类。 然后我定义了一个访问该类常量的类方法。 这很好用。 一个例子: #! /usr/bin/env ruby class NonInstantiableClass Const = “hello, world!” class << self def shout_my_constant puts Const.upcase end end end NonInstantiableClass.shout_my_constant 我的问题出现在尝试将此类方法移出到外部模块,如下所示: #! /usr/bin/env ruby module CommonMethods def shout_my_constant puts Const.upcase end end class NonInstantiableClass Const = “hello, world!” class << self include CommonMethods end end NonInstantiableClass.shout_my_constant Ruby将该方法解释为从模块而不是类中请求常量: line 5:in `shout_my_constant’: uninitialized […]