lib/eco/api/common/loaders/parser.rb in eco-helpers-2.0.25 vs lib/eco/api/common/loaders/parser.rb in eco-helpers-2.0.26

- old
+ new

@@ -1,11 +1,32 @@ module Eco module API module Common module Loaders - class Parser < Eco::API::Common::BaseLoader + class Parser < Eco::API::Common::Loaders::CaseBase + # Helper class to scope what required attributes it depends on + class RequiredAttrs < Struct.new(:attr, :type, :attrs) + def active?(*input_attrs) + missing(*input_attrs).empty? + end + + def dependant?(attr) + attrs.include?(attr) + end + + def missing(*input_attrs) + return [] if input_attrs.include?(attr) + match = input_attrs & attrs + miss = attrs - match + return [] if miss.empty? + return attrs if match.empty? + return miss if type == :all + [] + end + end + class << self attr_reader :active_when # @param value [String, Symbol] the attribute or type to be parsed/serialized # 1. when `String`: the internal name of the field/attribute this parser/serializer manages for. @@ -17,16 +38,18 @@ end name value @attribute = value end - # TODO: it migh rather merge? # Some parsers require dependencies to do their job. - def dependencies(value = nil) + def dependencies(**value) @dependencies ||= {} - return @dependencies unless value - @dependencies = value + return @dependencies.merge({ + required_attrs: @active_when_attrs + }) unless !value.empty? + raise "Expected Hash. Given: '#{value.class}'" unless value.is_a?(Hash) + @dependencies.merge!(value) end # Define or get the `phase` that the `parser` kicks in. # @param phase [Symbol] the phase when this parser should be active. # Must be one of [`:internal`, `:final`] @@ -45,17 +68,19 @@ @serializing_phase = phase end # Helper to build the `active_when` condition. def active_when_any(*attrs) + @active_when_attrs = RequiredAttrs.new(attribute, :any, attrs) @active_when = Proc.new do |source_data| keys = data_keys(source_data) attrs.any? {|key| keys.include?(key)} end end # Helper to build the `active_when` condition. def active_when_all(*attrs) + @active_when_attrs = RequiredAttrs.new(attribute, :all, attrs) @active_when = Proc.new do |source_data| keys = data_keys(source_data) attrs.all? {|key| keys.include?(key)} end end