@@ -3,20 +3,21 @@ module PolymorphicIntegerType
33 module Extensions
44 module ClassMethods
55
6- def belongs_to ( name , options = { } )
6+ def belongs_to ( name , scope = nil , options = { } )
7+ options = scope if scope . kind_of? Hash
78 integer_type = options . delete :integer_type
89 super
910 if options [ :polymorphic ] && integer_type
1011 mapping = PolymorphicIntegerType ::Mapping [ name ]
11- foreign_type = reflections [ name ] . foreign_type
12+ foreign_type = reflections [ name . to_s ] . foreign_type
1213 self . _polymorphic_foreign_types << foreign_type
1314
1415 define_method foreign_type do
1516 t = super ( )
1617 mapping [ t ]
1718 end
1819
19- define_method "#{ foreign_type } =" do |klass |
20+ define_method "#{ foreign_type } =" do |klass |
2021 enum = mapping . key ( klass . to_s )
2122 enum ||= mapping . key ( klass . base_class . to_s ) if klass . kind_of? ( Class ) && klass <= ActiveRecord ::Base
2223 enum ||= klass if klass != NilClass
@@ -37,7 +38,7 @@ def belongs_to(name, options = {})
3738 end
3839 end
3940
40- def remove_type_and_establish_mapping ( name , options )
41+ def remove_type_and_establish_mapping ( name , options , scope )
4142 integer_type = options . delete :integer_type
4243 if options [ :as ] && integer_type
4344 poly_type = options . delete ( :as )
@@ -47,24 +48,35 @@ def remove_type_and_establish_mapping(name, options)
4748
4849 options [ :foreign_key ] ||= "#{ poly_type } _id"
4950 foreign_type = options . delete ( :foreign_type ) || "#{ poly_type } _type"
50- options [ :conditions ] ||= { }
51- if options [ :conditions ] . is_a? ( Array )
52- cond = options [ :conditions ] . first
53- options [ :conditions ] [ 0 ] = "(#{ cond } ) AND #{ foreign_type } =#{ klass_mapping . to_i } "
54- else
55- options [ :conditions ] . merge! ( { foreign_type => klass_mapping . to_i } )
56- end
51+
52+ options [ :scope ] ||= -> {
53+ condition = where ( foreign_type => klass_mapping . to_i )
54+ condition = instance_exec ( &scope ) . merge ( condition ) if scope . is_a? ( Proc )
55+ condition
56+ }
57+ else
58+ options [ :scope ] ||= scope
5759 end
5860 end
5961
60- def has_many ( name , options = { } , &extension )
61- remove_type_and_establish_mapping ( name , options )
62- super ( name , options , &extension )
62+ def has_many ( name , scope = nil , options = { } , &extension )
63+ if scope . kind_of? Hash
64+ options = scope
65+ scope = nil
66+ end
67+
68+ remove_type_and_establish_mapping ( name , options , scope )
69+ super ( name , options . delete ( :scope ) , options , &extension )
6370 end
6471
65- def has_one ( name , options = { } )
66- remove_type_and_establish_mapping ( name , options )
67- super ( name , options )
72+ def has_one ( name , scope = nil , options = { } )
73+ if scope . kind_of? Hash
74+ options = scope
75+ scope = nil
76+ end
77+
78+ remove_type_and_establish_mapping ( name , options , scope )
79+ super ( name , options . delete ( :scope ) , options )
6880 end
6981
7082
0 commit comments