Sha256: 7eb944bf5326db90e4730b039dde653395aef3023d738a02191c3519ea5fb7d3

Contents?: true

Size: 1.88 KB

Versions: 1

Compression:

Stored size: 1.88 KB

Contents

require "unpolymorph/version"

module Unpolymorph

  def unpolymorph( name, associations, options = {} )

    scope "for_#{name}", -> obj { where( "#{obj.class.base_class.to_s.underscore}_id" => obj.id ) }

    if options[:create_associations]
      associations.each do |assoc|
        # Assoc name: string vs symbol make a difference here?
        belongs_to assoc.to_sym
      end
    end

    define_method( name ) do
      var_name = "@_unpolymorph_#{name}"
      value = instance_variable_get( var_name )
      return value if value
      associations.each do |assoc|
        value = send( assoc )
        if value
          instance_variable_set( var_name, value )
          return value
        end
      end
      return nil
    end

    define_method( "#{name}=" ) do |value|
      associations.each do |assoc|
        if value.class.base_class.to_s.underscore == assoc.to_s
          send( "#{assoc}=", value )
          instance_variable_set( "@_unpolymorph_#{name}", value )
          return
        end
      end
      raise ArgumentError, "Cannot set #{name} to #{value}, no association matches"
    end
    
    # For use in migrations
    define_singleton_method( "update_sql_#{name}_check" ) do |migration|
      required = options.has_key?( :required ) ? options[:required] : true
      constraint = required ? "exactly_one_unpolymorphic_#{name}" : "at_most_one_unpolymorphic_#{name}"
      migration.execute( "ALTER TABLE #{table_name} DROP CONSTRAINT IF EXISTS #{constraint}" )
      migration.execute( "ALTER TABLE #{table_name} ADD CONSTRAINT #{constraint} CHECK (#{associations.collect { |a| "(#{a}_id IS NOT NULL)::int" }.join( " + ")} #{required ? "=" : "<="} 1)" )
    end

    define_singleton_method( "possible_#{name}?" ) do |object|
      return associations.any? { |assoc| object.class.base_class.to_s.underscore == assoc.to_s }
    end
  end
end

ActiveRecord::Base.extend( Unpolymorph )

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
unpolymorph-0.2.1 lib/unpolymorph.rb