Sha256: 95632f4a3c85230b32929a0ce8be8342418ad79028caf21707843dd1658a4628

Contents?: true

Size: 1.49 KB

Versions: 1

Compression:

Stored size: 1.49 KB

Contents

module M2MFastInsert
  module HasAndBelongsToManyOverride
    extend ActiveSupport::Concern
    included do
      class_eval do
        # Create Method chain if habtm is defined - This is because it goes down to AR::Base
        # and errors because at the time of inclusion, there is none defined
        alias_method_chain :has_and_belongs_to_many, :fast_inserts if self.method_defined? :has_and_belongs_to_many
      end
    end

    # Rig the original habtm to call our method definition
    #
    # name - Plural name of the model we're associating with
    # options - see ActiveRecord docs
    def has_and_belongs_to_many_with_fast_inserts(name, options = {})
      has_and_belongs_to_many_without_fast_inserts(name, options)
      define_fast_methods_for_model(name, options)
    end

    private
    # Get necessary table and column information so we can define
    # fast insertion methods
    #
    # name - Plural name of the model we're associating with
    # options - see ActiveRecord docs
    def define_fast_methods_for_model(name, options)
      join_table = options[:join_table]
      join_column_name = name.to_s.downcase.singularize
      define_method "fast_#{join_column_name}_ids_insert" do |*args|
        table_name = self.class.table_name.singularize
        insert = M2MFastInsert::Base.new id, join_column_name, table_name, join_table, *args
        insert.fast_insert
      end
    end
  end
end
ActiveRecord::Associations::ClassMethods.send :include, M2MFastInsert::HasAndBelongsToManyOverride

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
m2m_fast_insert-0.1.0 lib/m2m_fast_insert/has_and_belongs_to_many_override.rb