Module: DelegateIfNil
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/delegate_if_nil.rb,
lib/delegate_if_nil/railtie.rb,
lib/delegate_if_nil/version.rb
Defined Under Namespace
Classes: Railtie
Constant Summary collapse
- VERSION =
"0.2.0"
Instance Method Summary collapse
Instance Method Details
#nil_delegate(*attrs, to:) ⇒ Object
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 |
# File 'lib/delegate_if_nil.rb', line 8 def nil_delegate(*attrs, to:) attrs.each do |attr| define_method attr do self[attr].nil? ? send(to)&.send(attr) : self[attr] end source_method = "#{attr}_source".to_sym define_method source_method do return "self" unless self[attr].nil? if send(to)&.respond_to?(source_method) to_source = send(to).send(source_method) return to.to_s if to_source == "self" return to_source else return send(to)&.send(attr).nil? ? "unset" : to.to_s end end delegted_bool_method = "#{attr}_delegated?".to_sym define_method delegted_bool_method do self[attr].nil? end end end |