Sha256: 863a8209c69153093448c1b75b3919235f2b1553fe593d758ebac135af8f2bd2

Contents?: true

Size: 1.29 KB

Versions: 2

Compression:

Stored size: 1.29 KB

Contents

require "unpolymorph/version"

module Unpolymorph

  def unpolymorph( name, associations )

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

    define_method( name ) do
      associations.each do |assoc|
        associated = send( assoc )
        return associated if associated
      end
    end

    define_method( "#{name}=" ) do |value|
      associations.each do |assoc|
        if value.class.base_class.to_s.underscore == assoc.to_s
          send( "#{assoc}=", 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|
      constraint = "exactly_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( " + ")} = 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

2 entries across 2 versions & 1 rubygems

Version Path
unpolymorph-0.1.2 lib/unpolymorph.rb
unpolymorph-0.1.1 lib/unpolymorph.rb