Ruby mixin和类常量

Ruby mixin和类常量,ruby,mixins,Ruby,Mixins,我有一个班级和一个模块: appointment.rb class Appointment < ActiveRecord::Base include Appointments::Events ALERT = "hello!" end class Appointment < ActiveRecord::Base ALERTS = "hello!" include Events end 打电话给#say_alert会让我: uninitialized con

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

appointment.rb

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

  ALERT = "hello!"

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

  include Events
end
打电话给#say_alert会让我:

uninitialized constant Module::ALERT

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

您按哪个顺序加载文件?以及如何调用#say_警报

此代码工作正常:

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

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

您按哪个顺序加载文件?以及如何调用#say_警报

此代码工作正常:

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

答案很简单

问题是我在常量定义之前在类中包含了模块。我还对我的代码进行了一些重构,以便它能够像@rbates在

现在我的代码起作用了:

app/models/appointment.rb

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

  ALERT = "hello!"

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

  include Events
end
$rails控制台

Appointment.last.say_alert
=> "hello!"

答案很简单,

问题是我在常量定义之前在类中包含了模块。我还对我的代码进行了一些重构,以便它能够像@rbates在

现在我的代码起作用了:

app/models/appointment.rb

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

  ALERT = "hello!"

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

  include Events
end
$rails控制台

Appointment.last.say_alert
=> "hello!"

可能重复:不知道ruby,但可能找不到警报是什么,可能是范围问题可能重复:不知道ruby,但可能找不到警报是什么,可能是范围问题混合约会::事件用于委托某些功能,因为约会模型太大,所以我需要调用Appointment.last.say_alert,它应该返回=>“hello!”。我看不出你的代码有什么不同,它真的对你有用吗?似乎你删除了extend ActiveSupport::Concern混合约会::事件用于委派一些功能,因为约会模型太大,所以我需要调用appoint.last.say_alert,它应该返回=>“hello!”。我看不出你的代码有什么不同,它真的对你有用吗?似乎你删除了extend ActiveSupport::Concern