Skip to content

Commit 90fad83

Browse files
author
Kyle d'Oliveira
authored
Merge pull request #24 from doliveirakn/prepend-to-prevent-overriding-the-dynamic-method
Use a dynamic module to include the writing methods that are generated from using belongs_to
2 parents 523ed07 + 64a7058 commit 90fad83

3 files changed

Lines changed: 30 additions & 16 deletions

File tree

lib/polymorphic_integer_type/extensions.rb

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -24,26 +24,32 @@ def belongs_to(name, scope = nil, **options)
2424
mapping
2525
end
2626

27-
define_method foreign_type do
28-
t = super()
29-
mapping[t]
30-
end
27+
foreign_type_extension = Module.new do
28+
define_method foreign_type do
29+
t = super()
30+
self.class.send("#{foreign_type}_mapping")[t]
31+
end
3132

32-
define_method "#{foreign_type}=" do |klass|
33-
enum = mapping.key(klass.to_s)
34-
if klass.kind_of?(Class) && klass <= ActiveRecord::Base
35-
enum ||= mapping.key(klass.base_class.to_s)
36-
enum ||= mapping.key(klass.base_class.sti_name)
33+
define_method "#{foreign_type}=" do |klass|
34+
mapping = self.class.send("#{foreign_type}_mapping")
35+
enum = mapping.key(klass.to_s)
36+
if klass.kind_of?(Class) && klass <= ActiveRecord::Base
37+
enum ||= mapping.key(klass.sti_name)
38+
enum ||= mapping.key(klass.base_class.to_s)
39+
enum ||= mapping.key(klass.base_class.sti_name)
40+
end
41+
enum ||= klass if klass != NilClass
42+
super(enum)
3743
end
38-
enum ||= klass if klass != NilClass
39-
super(enum)
40-
end
4144

42-
define_method "#{name}=" do |record|
43-
super(record)
44-
send("#{foreign_type}=", record.class)
45+
define_method "#{name}=" do |record|
46+
super(record)
47+
send("#{foreign_type}=", record.class)
48+
end
4549
end
4650

51+
include(foreign_type_extension)
52+
4753
validate do
4854
t = send(foreign_type)
4955
unless t.nil? || mapping.values.include?(t)
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
module PolymorphicIntegerType
2-
VERSION = "2.2.2"
2+
VERSION = "2.2.3"
33
end

spec/support/link.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,12 @@ class Link < ActiveRecord::Base
33

44
belongs_to :source, polymorphic: true, integer_type: true
55
belongs_to :target, polymorphic: true, integer_type: true
6+
7+
def source=(val)
8+
super(val)
9+
end
10+
11+
def source_type=(val)
12+
super(val)
13+
end
614
end

0 commit comments

Comments
 (0)