Skip to content

Commit 00078ce

Browse files
author
Yu Lin
committed
fixes for rails 4
1 parent 37e4a75 commit 00078ce

1 file changed

Lines changed: 23 additions & 8 deletions

File tree

lib/polymorphic_integer_type/extensions.rb

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ def belongs_to(name, scope = nil, options = {})
1717
mapping[t]
1818
end
1919

20-
define_method "#{foreign_type}=" do |klass|
20+
define_method "#{foreign_type}=" do |klass|
2121
enum = mapping.key(klass.to_s)
2222
enum ||= mapping.key(klass.base_class.to_s) if klass.kind_of?(Class) && klass <= ActiveRecord::Base
2323
enum ||= klass if klass != NilClass
@@ -38,7 +38,7 @@ def belongs_to(name, scope = nil, options = {})
3838
end
3939
end
4040

41-
def remove_type_and_establish_mapping(name, options)
41+
def remove_type_and_establish_mapping(name, options, scope)
4242
integer_type = options.delete :integer_type
4343
if options[:as] && integer_type
4444
poly_type = options.delete(:as)
@@ -48,19 +48,34 @@ def remove_type_and_establish_mapping(name, options)
4848

4949
options[:foreign_key] ||= "#{poly_type}_id"
5050
foreign_type = options.delete(:foreign_type) || "#{poly_type}_type"
51-
options[:scope] ||= ->(n){where(foreign_type => klass_mapping.to_i)}
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
5259
end
5360
end
5461

5562
def has_many(name, scope = nil, options = {}, &extension)
56-
options = scope if scope.kind_of? Hash
57-
remove_type_and_establish_mapping(name, options)
58-
super(name, options.delete(:scope), 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)
5970
end
6071

6172
def has_one(name, scope = nil, options = {})
62-
options = scope if scope.kind_of? Hash
63-
remove_type_and_establish_mapping(name, 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)
6479
super(name, options.delete(:scope), options)
6580
end
6681

0 commit comments

Comments
 (0)