Class: Appetizer::Populator
- Inherits:
-
Object
- Object
- Appetizer::Populator
- Defined in:
- lib/appetizer/populator.rb
Overview
Helps assign values from a low-level structure to a rich domain model. Most useful as an explicit alternative to ActiveRecord’s mass-assignment, with an AR object as the target and a params hash as the source.
Defined Under Namespace
Modules: Helpers
Instance Attribute Summary collapse
-
#source ⇒ Object
readonly
Returns the value of attribute source.
-
#target ⇒ Object
readonly
Returns the value of attribute target.
Instance Method Summary collapse
-
#initialize(target, source) {|_self| ... } ⇒ Populator
constructor
A new instance of Populator.
- #nested(key, target = nil, &block) ⇒ Object
- #set(key, value = nil) ⇒ Object
- #set!(key, value, &block) ⇒ Object
Constructor Details
#initialize(target, source) {|_self| ... } ⇒ Populator
Returns a new instance of Populator.
12 13 14 15 16 17 |
# File 'lib/appetizer/populator.rb', line 12 def initialize target, source, &block @target = target @source = source yield self if block_given? end |
Instance Attribute Details
#source ⇒ Object (readonly)
Returns the value of attribute source.
10 11 12 |
# File 'lib/appetizer/populator.rb', line 10 def source @source end |
#target ⇒ Object (readonly)
Returns the value of attribute target.
9 10 11 |
# File 'lib/appetizer/populator.rb', line 9 def target @target end |
Instance Method Details
#nested(key, target = nil, &block) ⇒ Object
19 20 21 22 23 24 |
# File 'lib/appetizer/populator.rb', line 19 def nested key, target = nil, &block source = self.source[key] || self.source[key.intern] target ||= self.target.send key Populator.new target, source, &block if source end |
#set(key, value = nil) ⇒ Object
26 27 28 29 30 31 |
# File 'lib/appetizer/populator.rb', line 26 def set key, value = nil value ||= source[key] || source[key.intern] return if value.nil? || (value.respond_to?(:empty?) && value.empty?) set! key, value end |
#set!(key, value, &block) ⇒ Object
33 34 35 |
# File 'lib/appetizer/populator.rb', line 33 def set! key, value, &block block ? block[value] : target.send("#{key}=", value) end |