Module: LazyRecord::Associations
- Includes:
- Nesting
- Defined in:
- lib/lazy_record/associations.rb
Overview
Set up in-memory one-to-one associations between POROs.
Constant Summary
collapse
- ASSOCIATION_MODULE_NAME =
:Associations
Instance Method Summary
collapse
Methods included from Nesting
#apply_nesting, #apply_nesting_one_level_back, #lazy_const_get, #lazy_const_get_one_level_back
Instance Method Details
#add_has_one_methods(args) ⇒ Object
18
19
20
21
22
23
24
25
|
# File 'lib/lazy_record/associations.rb', line 18
def add_has_one_methods(args)
define_has_one_associations(*args)
define_has_one_associations_to_s
args.each do |association|
define_association_setter(association)
define_association_getter(association)
end
end
|
#define_association_getter(association) ⇒ Object
50
51
52
53
54
|
# File 'lib/lazy_record/associations.rb', line 50
def define_association_getter(association)
define_method(association) do
instance_variable_get("@#{association}")
end
end
|
#define_association_setter(assoc) ⇒ Object
42
43
44
45
46
47
48
|
# File 'lib/lazy_record/associations.rb', line 42
def define_association_setter(assoc)
klass = lazy_const_get_one_level_back(assoc.to_s.camelize).call
define_method("#{assoc}=") do |val|
return instance_variable_set("@#{assoc}", val) if val.is_a? klass
raise ArgumentError, "Argument must be a #{klass}"
end
end
|
#define_has_one_associations(*args) ⇒ Object
27
28
29
30
31
|
# File 'lib/lazy_record/associations.rb', line 27
def define_has_one_associations(*args)
define_method(:associations) do
args
end
end
|
#define_has_one_associations_to_s ⇒ Object
33
34
35
36
37
38
39
40
|
# File 'lib/lazy_record/associations.rb', line 33
def define_has_one_associations_to_s
define_method(:associations_to_s) do
associations.map do |association|
"#{association}: #{stringify_value(send(association))}"
end
end
private :associations_to_s
end
|
#lr_has_one(*args) ⇒ Object
12
13
14
15
16
|
# File 'lib/lazy_record/associations.rb', line 12
def lr_has_one(*args)
include mod = get_or_set_mod(ASSOCIATION_MODULE_NAME)
mod.extend(Associations) unless mod.const_defined?('Associations')
mod.module_eval { add_has_one_methods(args) }
end
|