Простое расширение железнодорожного транспорта активной записи

StackOverflow https://stackoverflow.com/questions/4253694

  •  27-09-2019
  •  | 
  •  

Вопрос

Я создаю рельсы 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 модели. Пожалуйста помоги! Я чрезвычайно разочарован этим, казалось бы, тривиальным кодексом! Спасибо!

Это было полезно?

Решение

Вы определяете self.include (4-я линия вниз), когда правильный метод self.included.

Другие советы

Вы можете упростить код с помощью 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/

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top