Simple Railtie Extension of Active Record
-
27-09-2019 - |
문제
I'm creating a Rails 3.0.3 gem and can't get it to work:
# 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
I get undefined local variable or method 'acts_as_fail'
when I add acts_as_fail
to any of my ActiveRecord
models. Please help! I'm extremely frustrated with this seemingly trivial code! Thanks!
해결책
You're defining self.include
(4th line down), when the correct method is self.included
.
다른 팁
You can simplify the code by using extend
directly:
# 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
This is a good read: http://yehudakatz.com/2009/11/12/better-ruby-idioms/
제휴하지 않습니다 StackOverflow