Rails定制类Gem

时间:2016-02-08 17:24:14

标签: ruby-on-rails ruby metaprogramming

我在我的rails应用程序中重新打开了一个gem类,一切似乎都没问题,一切运行良好,但几分钟后,似乎我的应用程序忘记了所有修改:

配置/初始化/ rapidfire_custom.rb

::Rapidfire::Survey.class_eval do

  belongs_to :campaign, class_name: '::Campaign', inverse_of: :survey

  before_create :default_active
  before_validation :default_status, :default_name

  STATUS = ['DRAFT', 'PUBLISHED']
  validates_inclusion_of :status, in: STATUS
  validates :name, presence: true

  scope :from_company, -> (id) { where(company_id: id) }
  scope :template, -> { where(campaign_id: nil) }
  scope :published, -> { where(status: 'PUBLISHED') }

  def default_active
    self.active ||= true
  end

  def default_status
    self.status ||= 'DRAFT'
  end

  def self.all_status
    STATUS
  end

  def default_name
    if self.campaign
      self.name = 'Survey'
    end
  end

end

错误:

undefined method `template' for #<Rapidfire::Survey::ActiveRecord_AssociationRelation:0x007fc762215ad0>

只有在开发时才会发生,我正在使用puma:

配置/ puma.rb

workers Integer(ENV['WEB_CONCURRENCY'] || 2)
threads_count = Integer(ENV['MAX_THREADS'] || 5)
threads threads_count, threads_count

preload_app!

rackup      DefaultRackup
port        ENV['PORT']     || 3000
environment ENV['RACK_ENV'] || 'development'

if ENV['RACK_ENV'].nil? || ENV['RACK_ENV'] == 'development'
  ssl_bind 'my_website.dev', '3000', { key: 'ssl/device.key', cert: 'ssl/device.crt' }
end

on_worker_boot do
  ActiveRecord::Base.establish_connection
  $redis.client.reconnect
end

我不知道发生了什么,有什么想法吗?

由于

1 个答案:

答案 0 :(得分:2)

我猜测当ActiveRecord实例化Rapidfire::Survey条记录时,它会从gem加载类 - 这会使您在初始化程序中对类eval所做的更改无效。

如果您需要覆盖库方法并且没有更好的方法,那么只应该真正完成对不属于您的对象进行修补。

您还需要考虑类eval发生的时间和位置 - 初始化器在rails应用程序加载时运行,而模型类在ActiveRecord需要时延迟加载。因此,使用初始化程序来配置模型并不是一个好主意。

使用继承是正确的做法 - 您正在创建自己的域对象。

相关问题