lib/eco/language/models/parser_serializer.rb in eco-helpers-2.6.4 vs lib/eco/language/models/parser_serializer.rb in eco-helpers-2.7.0

- old
+ new

@@ -45,26 +45,34 @@ # Calls the `parser` of this attribute by passing `source` and resolved dependencies. # @note # - the method depenencies override keys of the _default dependencies_. # @raise [Exception] when there is **no** `parser` defined. + # @yield [key, value] the dependency resolver. The block is called is value is a Proc. + # @yieldparam key [Symbol] the dependency key name. + # @yieldparam value [Any] the depedency value. + # @yieldreturn value the new value # @param source [Any] source data to be parsed. # @param dependencies [Hash] _additional dependencies_ that should be merged to the _default dependencies_. - def parse(source, category = :default, dependencies: {}) + def parse(source, category = :default, dependencies: {}, &block) raise "There is no parser of type '#{category}' for this attribue '#{attr}'" unless parser_category?(category) - call_block(source, @dependencies.merge(dependencies), attr, &@parser[category.to_sym]) + + deps = resolve_dependencies(@dependencies.merge(dependencies), &block) + call_block(source, deps, attr, &@parser[category.to_sym]) end # Calls the `serializer` of this attribute by passing `object` and resolved dependencies. # @note # - the method depenencies override keys of the _default dependencies_. # @raise [Exception] when there is **no** `serializer` defined. # @param object [Any] source data to be serialized. # @param dependencies [Hash] _additional dependencies_ that should be merged to the _default dependencies_. - def serialize(object, category = :default, dependencies: {}) + def serialize(object, category = :default, dependencies: {}, &block) raise "There is no serializer of type '#{category}' for this attribue '#{attr}'" unless serializer_category?(category) - call_block(object, @dependencies.merge(dependencies), attr, &@serializer[category.to_sym]) + + deps = resolve_dependencies(@dependencies.merge(dependencies), &block) + call_block(object, deps, attr, &@serializer[category.to_sym]) end # Checks if there's a `parser` defined for `category` # @return [Boolean] `true` if the parser is defined, and `false` otherwise def parser_category?(category = :default) @@ -77,16 +85,27 @@ @serializer.key?(category.to_sym) end private + # For each Proc value it yields to resolve the dependency + def resolve_dependencies(deps) + return deps unless block_given? + + deps.dup.tap do |out| + deps.each do |key, value| + next unless value.is_a?(Proc) + out[key] = yield(key, value) + end + end + end + # The methods may expect less parameters from some type of parsers. # Here, we ensure they are called with the expected number of parameters. def call_block(*args, &block) params = block.parameters.zip(args).map(&:last) yield(*params) end - end end end end