Ruby on rails 如何从模块中引用的类常量数组对方法进行元编程?

Ruby on rails 如何从模块中引用的类常量数组对方法进行元编程?,ruby-on-rails,ruby,inheritance,Ruby On Rails,Ruby,Inheritance,我编写了一个基本的可事件模块,允许其他类为自己创建事件。所有模型都有自己的一组事件,例如消息正在发送或用户有登录事件。我想在类级别创建一个事件数组作为常量,并在模块内访问该数组,以构建用于创建以下事件的帮助器方法: class User EVENT_TYPES = ['sign_in', 'sign_out'] include Eventable end 这样做的问题是:没有正确定义方法。它无法正确引用相应模型的常量事件类型 我怎样才能从一个模块中访问一个类常量呢?我想说,使用这样

我编写了一个基本的可事件模块,允许其他类为自己创建事件。所有模型都有自己的一组事件,例如
消息
正在
发送
用户
登录
事件。我想在类级别创建一个事件数组作为常量,并在模块内访问该数组,以构建用于创建以下事件的帮助器方法:

class User
  EVENT_TYPES = ['sign_in', 'sign_out']
  include Eventable
end


这样做的问题是:没有正确定义方法。它无法正确引用相应模型的常量
事件类型


我怎样才能从一个模块中访问一个类常量呢?

我想说,使用这样的常量不是很鲁比。这更为惯用(至少在rails中是这样)

这里是实现

module Eventable
  extend ActiveSupport::Concern

  module ClassMethods
    def event_types(*names)
      names.each do |event_type|
        define_method "create_#{event_type}_event" do |args={}|
          Event.create(eventable: self, event_type: event_type)
        end
      end
    end
  end
end

常数可以通过
模块#const_get
方法获得。但我不会将单个类的事件类型表示为常量,而是表示为属于该类的类方法或实例变量:

class User
  def self.event_types
    [:sign_in, :sign_out]
  end
end

# or

class User
  @event_types = [:sign_in, :sign_out]

  class << self
    attr_reader :event_types
  end
end
类用户
def self.event_类型
[:登录,:注销]
结束
结束
#或
类用户
@事件类型=[:登录,:注销]

全班感谢Boris,我希望我能接受两个答案,因为这两个答案都非常有效。不管怎样,Sergio的答案比我的好,对他来说+1。Segio,我可以问一下
事件
事件。创建
?我对Rails不是很精通,但我想这些都是由
has\u many:events
行带来的。你能给我指一下记录这一点的页面吗?@BorisStitnicky:
事件
很可能是一个活动记录模型(它有
创建
方法)
有许多
是活动记录中的一种方法,它定义了
事件
事件ID
等方法。这里有很多信息:请原谅我的无知,只是为了完全确定,如果
Event
类不存在,
有很多:events
方法不会为我们构造它,是吗?@BorisStitnicky:不,不会。相反,我认为这会引起一个错误。
class Message
  include Eventable

  event_types :sent, :opened
end
module Eventable
  extend ActiveSupport::Concern

  module ClassMethods
    def event_types(*names)
      names.each do |event_type|
        define_method "create_#{event_type}_event" do |args={}|
          Event.create(eventable: self, event_type: event_type)
        end
      end
    end
  end
end
class User
  def self.event_types
    [:sign_in, :sign_out]
  end
end

# or

class User
  @event_types = [:sign_in, :sign_out]

  class << self
    attr_reader :event_types
  end
end