Sha256: 4f176638eb0d581576634030845b4d53a2d6ef49e45b14c21f786f05cc5e5e5f

Contents?: true

Size: 1.17 KB

Versions: 5

Compression:

Stored size: 1.17 KB

Contents

require 'active_support/concern'

module Ardm
  module Ar
    module Inheritance
      extend ActiveSupport::Concern

      included do
        # ActiveRecord would prefer that you not use the column "type"
        # for anything other than single table inheritance.
        # The solution is to point ActiveRecord elsewhere.
        unless respond_to?(:inheritance_column=)
          class_attribute :inheritance_column
        end
        self.inheritance_column = "override-active-record-default-sti-column-type"
      end

      module ClassMethods
        def new(attrs={}, *a, &b)
          type = attrs && attrs.stringify_keys[inheritance_column.to_s]
          if type && type != name && type != self
            #puts "STI found for #{type} #{self}"
            con = type.is_a?(Class) ? type : type.constantize
            if con < self
              con.new(attrs, *a, &b)
            else
              raise "Tried to create subclass from #{type} (from key #{inheritance_column}) that is not a subclass of #{name}."
            end
          else
            #puts "No STI found for #{self} (#{attrs.inspect})"
            super
          end
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
ardm-0.4.0.ar427 lib/ardm/ar/inheritance.rb
ardm-0.4.0 lib/ardm/ar/inheritance.rb
ardm-0.3.2 lib/ardm/ar/inheritance.rb
ardm-0.3.1 lib/ardm/ar/inheritance.rb
ardm-0.3.0 lib/ardm/ar/inheritance.rb