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
|
# File 'lib/br_nfe/active_model/has_one.rb', line 6
def has_one attr_name, class_name, *args
options = {null: true, inverse_of: :reference}.merge(args.)
define_method attr_name do |&block|
block.call(send("#{attr_name}_force_instance")) if block
if instance_variable_get("@#{attr_name}").is_a?(eval(class_name))
instance_variable_get("@#{attr_name}").instance_variable_set("@#{options[:inverse_of]}", self) if instance_variable_get("@#{attr_name}").send(options[:inverse_of]).blank?
instance_variable_get("@#{attr_name}")
else
if options[:null] then nil else send("#{attr_name}_force_instance") end
end
end
define_method "#{attr_name}=" do |value|
if value.is_a?(eval(class_name))
instance_variable_set("@#{attr_name}", value)
elsif value.is_a?(Hash)
send("#{attr_name}_force_instance").assign_attributes(value)
elsif value.blank?
instance_variable_set("@#{attr_name}", nil)
end
end
define_method "#{attr_name}_force_instance" do
instance_variable_set("@#{attr_name}", eval(class_name).new) unless instance_variable_get("@#{attr_name}").is_a?(eval(class_name))
instance_variable_get("@#{attr_name}").instance_variable_set("@#{options[:inverse_of]}", self) if instance_variable_get("@#{attr_name}").send(options[:inverse_of]).blank?
instance_variable_get("@#{attr_name}")
end
end
|