活动记录的简单铁路延伸

时间:2010-11-23 07:24:51

标签: ruby-on-rails ruby railtie

我正在创建一个Rails 3.0.3 gem并且无法让它工作:

# attached.rb
module Attached
  require 'attached/railtie' if defined?(Rails)
  def self.include(base)
    base.send :extend, ClassMethods
  end
  module ClassMethods
    def acts_as_fail
    end
  end
end

# attached/railtie.rb
require 'attached'
require 'rails'

module Attached
  class Railtie < Rails::Railtie
    initializer 'attached.initialize' do
      ActiveSupport.on_load(:active_record) do
        ActiveRecord::Base.send :include, Attached
      end
    end
  end
end

当我将undefined local variable or method 'acts_as_fail'添加到任何acts_as_fail模型时,我得到ActiveRecord。请帮忙!我对这个看似琐碎的代码感到非常沮丧!谢谢!

2 个答案:

答案 0 :(得分:4)

当正确的方法为self.include时,您正在定义self.included(第4行)。

答案 1 :(得分:3)

您可以直接使用extend简化代码:

# attached.rb
module Attached
  require 'attached/railtie' if defined?(Rails)
  def acts_as_fail
  end
end

# attached/railtie.rb
require 'attached'
require 'rails'

module Attached
  class Railtie < Rails::Railtie
    initializer 'attached.initialize' do
      ActiveSupport.on_load(:active_record) do
        ActiveRecord::Base.send :extend, Attached
      end
    end
  end
end

这是一个很好的阅读: http://yehudakatz.com/2009/11/12/better-ruby-idioms/