代码之家  ›  专栏  ›  技术社区  ›  Kevin Sylvestre

活动记录的简单Railtie扩展

  •  0
  • Kevin Sylvestre  · 技术社区  · 14 年前

    我正在创建一个Rails 3.0.3gem,但无法运行:

    # 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 回复  |  直到 13 年前
        1
  •  4
  •   Ryan Bigg Andrés Bonilla    14 年前

    你在定义 self.include 当正确的方法是 self.included .

        2
  •  3
  •   Petrik de Heus    14 年前

    您可以使用 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/