Kevin Sylvestre
Kevin Sylvestre

Reputation: 38052

Simple Railtie Extension of Active Record

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!

Upvotes: 0

Views: 1742

Answers (2)

Petrik de Heus
Petrik de Heus

Reputation: 970

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/

Upvotes: 3

Ryan Bigg
Ryan Bigg

Reputation: 107728

You're defining self.include (4th line down), when the correct method is self.included.

Upvotes: 4

Related Questions