加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何从模块中引用的类常量数组中编写元编程方

发布时间:2020-12-17 03:17:32 所属栏目:百科 来源:网络整理
导读:我编写了一个基本的Eventable模块,允许其他类为自己创建事件.所有模型都有自己的一组事件,例如发送消息或具有sign_in事件的用户.我想在类级别创建一个事件数组作为常量,并访问模块内部的数组,以构建辅助方法来创建如下事件: class User EVENT_TYPES = ['sig
我编写了一个基本的Eventable模块,允许其他类为自己创建事件.所有模型都有自己的一组事件,例如发送消息或具有sign_in事件的用户.我想在类级别创建一个事件数组作为常量,并访问模块内部的数组,以构建辅助方法来创建如下事件:

class User
  EVENT_TYPES = ['sign_in','sign_out']
  include Eventable
end
class Message
  EVENT_TYPES = ['sent','opened']
  include Eventable
end
module Eventable
  extend ActiveSupport::Concern

  included do
    has_many :events,as: :eventable
    attr_accessor :metadata

    self::EVENT_TYPES.each do |event_type|
      define_method "create_#{event_type}_event" do |args={}|
        Event.create(eventable: self,event_type: event_type)
      end
    end
  end
end

这个问题是:方法没有正确定义.它无法正确引用相应模型的常量EVENT_TYPES.

如何从模块中获取类常量?

解决方法

我会说,使用这样的常数不是非常rubyesque.这更加惯用(至少在轨道上).

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读