0

我正在创建一个 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模型时,我都会得到。请帮忙!我对这个看似微不足道的代码感到非常沮丧!谢谢!

4

2 回答 2

4

当正确self.include的方法是self.included.

于 2010-11-23T09:00:23.840 回答
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/

于 2010-11-23T10:29:59.217 回答