首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mixins和类常量

Mixins和类常量
EN

Stack Overflow用户
提问于 2016-02-18 22:54:39
回答 2查看 498关注 0票数 1

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

appointment.rb

代码语言:javascript
复制
class Appointment < ActiveRecord::Base
  include Appointments::Events

  ALERT = "hello!"

end

events.rb

代码语言:javascript
复制
module Appointments
  module Events
    extend ActiveSupport::Concern

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

#say_alert打电话给我:

代码语言:javascript
复制
uninitialized constant Module::ALERT
EN

回答 2

Stack Overflow用户

发布于 2016-02-18 23:13:44

对不起,没有回答,但是代码太长,不能发表评论:

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

此代码运行良好:

代码语言:javascript
复制
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

代码语言:javascript
复制
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

票数 0
EN

Stack Overflow用户

发布于 2016-02-19 18:39:39

答案很简单,

问题是,在常量定义之前,我在类中包含了模块。我还对代码进行了一些重构,这样它就像@rbates在http://railscasts.com/episodes/398-service-objects上建议的那样正确地使用了关注点

现在我的代码起作用了:

应用程序/模型/任命。

代码语言:javascript
复制
class Appointment < ActiveRecord::Base  
  ALERTS = "hello!"

  include Events
end

应用程序/模型/关注事项/约会/事件app

代码语言:javascript
复制
class Appointment
  module Events
    extend ActiveSupport::Concern

    def say_alert
     puts ALERT
    end
  end
end

$ rails控制台

代码语言:javascript
复制
Appointment.last.say_alert
=> "hello!"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35494128

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档