Mixins和类常量

时间:2016-02-18 22:54:39

标签: ruby mixins

我有1个课程和1个模块:

appointment.rb

module Appointments
  module Events
    extend ActiveSupport::Concern

    def say_alert
      puts self.class::ALERT
    end
  end
end

events.rb

uninitialized constant Module::ALERT

致电 #say_alert 告诉我:

Bar.js

2 个答案:

答案 0 :(得分:0)

抱歉,没有答案,但代码太长,无法发表评论:

您加载文件的顺序是什么?如何调用#say_alert?

此代码可以正常工作:

ActiveSupport::Concern

评论后: 它也适用于require 'active_support' module Appointments module Events extend ActiveSupport::Concern def say_alert puts self.class::ALERT end end end class Appointment include Appointments::Events ALERT = "hello!" end Appointment.new.say_alert

Setup.cs

我使用ruby 2.1.5

答案 1 :(得分:0)

答案很简单,

问题是我在常量定义之前将模块包含在我的类中。我还重构了我的代码,因此正如@rbates在http://railscasts.com/episodes/398-service-objects建议的那样正确地使用了关注点

现在我的代码有效:

应用程序/模型/ appointment.rb

class Appointment < ActiveRecord::Base  
  ALERTS = "hello!"

  include Events
end

应用程序/模型/关切/约会/ events.rb

class Appointment
  module Events
    extend ActiveSupport::Concern

    def say_alert
     puts ALERT
    end
  end
end

$ rails console

Appointment.last.say_alert
=> "hello!"