Class: LcpRuby::ModelFactory::ComputedApplicator
- Inherits:
-
Object
- Object
- LcpRuby::ModelFactory::ComputedApplicator
- Defined in:
- lib/lcp_ruby/model_factory/computed_applicator.rb
Class Method Summary collapse
Instance Method Summary collapse
- #apply! ⇒ Object
-
#initialize(model_class, model_definition) ⇒ ComputedApplicator
constructor
A new instance of ComputedApplicator.
Constructor Details
#initialize(model_class, model_definition) ⇒ ComputedApplicator
Returns a new instance of ComputedApplicator.
4 5 6 7 |
# File 'lib/lcp_ruby/model_factory/computed_applicator.rb', line 4 def initialize(model_class, model_definition) @model_class = model_class @model_definition = model_definition end |
Class Method Details
.compute(record, config) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/lcp_ruby/model_factory/computed_applicator.rb', line 21 def self.compute(record, config) case config when String # Template interpolation: "{first_name} {last_name}" config.gsub(/\{(\w+)\}/) { record.send(Regexp.last_match(1)).to_s } when Hash service_key = config["service"] || config[:service] return unless service_key service = Services::Registry.lookup("computed", service_key.to_s) unless service Rails.logger.warn("[LcpRuby] Computed service '#{service_key}' not found") if defined?(Rails) return end service.call(record) end end |
Instance Method Details
#apply! ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/lcp_ruby/model_factory/computed_applicator.rb', line 9 def apply! computed_fields = collect_computed_fields return if computed_fields.empty? @model_class.before_save do |record| computed_fields.each do |field_name, config| value = ComputedApplicator.compute(record, config) record.send("#{field_name}=", value) end end end |