/
has_postal_address.rb
57 lines (44 loc) · 1.47 KB
/
has_postal_address.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
module PostallyAddressable
module Model
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def has_postal_address(options = {})
# default options
options = {
eager_load: true
}.merge(options)
if options[:eager_load]
default_scope { includes(:postal_address) }
end
has_one :postal_address, as: :postally_addressable, autosave: true, dependent: :destroy
# getters
delegate *PostalAddress::DELEGATABLE_ATTRIBUTES.map{ |a| a.to_sym }, to: :postal_address
# setters
delegate *PostalAddress::DELEGATABLE_ATTRIBUTES.map{ |a| (a + "=").to_sym }, to: :postal_address
# query methods
delegate *PostalAddress::DELEGATABLE_ATTRIBUTES.map{ |a| (a + "?").to_sym }, to: :postal_address
# methods
delegate *PostalAddress::DELEGATABLE_METHODS.map{ |m| m.to_sym }, to: :postal_address
# prefixed methods
delegate *PostalAddress::PREFIXED_DELEGATABLE_METHODS.map{ |m| m.to_sym }, to: :postal_address, prefix: true
send :include, InstanceMethods
end
end
module InstanceMethods
def postal_address
return super if super
self.postal_address = PostalAddress.new({
postally_addressable: self
})
end
def initialize(*args)
super {}
if args[0]
self.attributes = args[0]
end
end
end
end
end