我有一个课程和一个模块:
appointment.rb
class Appointment < ActiveRecord::Base
include Appointments::Events
ALERT = "hello!"
endevents.rb
module Appointments
module Events
extend ActiveSupport::Concern
def say_alert
puts self.class::ALERT
end
end
end给#say_alert打电话给我:
uninitialized constant Module::ALERT发布于 2016-02-18 23:13:44
对不起,没有回答,但是代码太长,不能发表评论:
按什么顺序加载文件?以及如何调用#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我用红宝石2.1.5
发布于 2016-02-19 18:39:39
答案很简单,
问题是,在常量定义之前,我在类中包含了模块。我还对代码进行了一些重构,这样它就像@rbates在http://railscasts.com/episodes/398-service-objects上建议的那样正确地使用了关注点
现在我的代码起作用了:
应用程序/模型/任命。
class Appointment < ActiveRecord::Base
ALERTS = "hello!"
include Events
end应用程序/模型/关注事项/约会/事件app
class Appointment
module Events
extend ActiveSupport::Concern
def say_alert
puts ALERT
end
end
end$ rails控制台
Appointment.last.say_alert
=> "hello!"https://stackoverflow.com/questions/35494128
复制相似问题