ruby-on-rails – Ruby on Rails实例与类方法
发布时间:2020-12-17 01:35:31 所属栏目:百科 来源:网络整理
导读:我研究了 Ruby类,实例方法和我发现的主要区别之间的主要区别是我们不需要创建该类的实例,我们可以直接在类名上直接调用该方法. class Notifier def reminder_to_unconfirmed_user(user) headers['X-SMTPAPI'] = '{"category": "confirmation_reminder"}' @us
我研究了
Ruby类,实例方法和我发现的主要区别之间的主要区别是我们不需要创建该类的实例,我们可以直接在类名上直接调用该方法.
class Notifier def reminder_to_unconfirmed_user(user) headers['X-SMTPAPI'] = '{"category": "confirmation_reminder"}' @user = user mail(:to => @user["email"],:subject => "confirmation instructions reminder") end end 所以,在这里我在Notifier类中定义了实例方法reminder_to_unconfirmed_user,以便向未经证实的用户发送电子邮件,当我运行Notifier.reminder_to_unconfirmed_user(User.last)时,如果它是实例方法而不是类方法,则会调用它. 解决方法
要定义类方法,请在方法的定义(或类的名称)中使用self关键字:
class Notifier def self.this_method_is_a_class_method end def Notifier.this_one_is_a_class_method_too end def this_method_is_an_instance_method end end 在您的情况下,应将reminder_to_unconfirmed_user定义为类方法: class Notifier def self.reminder_to_unconfirmed_user(user) # ... end end 然后你可以像这样使用它: Notifier.reminder_to_unconfirmed_user(User.last) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |