【问题标题】:Mixins and class constantsMixin 和类常量
【发布时间】:2016-02-18 22:54:39
【问题描述】:

我有 1 个班级和 1 个模块:

约会.rb

class Appointment < ActiveRecord::Base
  include Appointments::Events

  ALERT = "hello!"

end

events.rb

module Appointments
  module Events
    extend ActiveSupport::Concern

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

调用 #say_alert 给我:

uninitialized constant Module::ALERT

【问题讨论】:

标签: ruby mixins


【解决方案1】:

答案很简单,

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

现在我的代码可以工作了:

app/models/appointment.rb

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

  include Events
end

app/models/concerns/appointment/events.rb

class Appointment
  module Events
    extend ActiveSupport::Concern

    def say_alert
     puts ALERT
    end
  end
end

$ rails 控制台

Appointment.last.say_alert
=> "hello!"

【讨论】:

    【解决方案2】:

    对不起,没有答案,但代码太长,无法评论:

    您按什么顺序加载文件?以及如何调用#say_alert?

    这段代码运行良好:

    module Appointments
      module Events
        def say_alert
          puts self.class::ALERT
        end
      end
    end
    
    class Appointment 
      include Appointments::Events
    
      ALERT = "hello!"
    
    end
    
    Appointment.new.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
    

    我使用 ruby​​ 2.1.5

    【讨论】:

    • 混合 Appointments::Events 用于委托一些功能,因为 Appointment 模型太大,所以我需要调用 Appointment.last.say_alert 它应该返回 =>“hello!”。我看不出你的代码有什么不同,它真的对你有用吗?
    • 您似乎删除了扩展 ActiveSupport::Concern
    猜你喜欢
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    相关资源
    最近更新 更多