Sha256: 2ee547146fe5c76c4766ad2834a4f820f935e87f39b208f5c4bd87d88e31682d

Contents?: true

Size: 1.19 KB

Versions: 4

Compression:

Stored size: 1.19 KB

Contents

require 'dry/core/inflector'
require 'dry/view/part'

module Dry
  module View
    class Decorator
      attr_reader :config

      # @api public
      def call(name, value, renderer:, context:, **options)
        klass = part_class(name, value, options)

        if value.respond_to?(:to_ary)
          singular_name = Dry::Core::Inflector.singularize(name).to_sym
          singular_options = singularize_options(options)

          arr = value.to_ary.map { |obj|
            call(singular_name, obj, renderer: renderer, context: context, **singular_options)
          }

          klass.new(name: name, value: arr, decorator: self, renderer: renderer, context: context)
        else
          klass.new(name: name, value: value, decorator: self, renderer: renderer, context: context)
        end
      end

      # @api public
      def part_class(name, value, **options)
        if options[:as].is_a?(Hash)
          options[:as].keys.first
        else
          options.fetch(:as) { Part }
        end
      end

      private

      # @api private
      def singularize_options(**options)
        options[:as] = options[:as].values.first if options[:as].is_a?(Hash)
        options
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
dry-view-0.5.3 lib/dry/view/decorator.rb
dry-view-0.5.2 lib/dry/view/decorator.rb
dry-view-0.5.1 lib/dry/view/decorator.rb
dry-view-0.5.0 lib/dry/view/decorator.rb