Sha256: 76ef93085493a5b39375bce0a1946d9039ce61f0969f4336bda77985d626aa84

Contents?: true

Size: 1.94 KB

Versions: 5

Compression:

Stored size: 1.94 KB

Contents

module Yaks
  class Runner
    include Util
    include Anima.new(:object, :config, :options)
    include Adamantium::Flat
    extend Forwardable

    def_delegators :config,        :policy, :default_format, :format_options_hash,
                                   :primitivize, :serializers
    def_delegators :format_class,  :media_type, :format_name

    def call
      Pipeline.new(steps).insert_hooks(hooks).call(object, env)
    end

    def read
      Pipeline.new([[:parse, serializer.inverse], [:format, formatter.inverse]]).insert_hooks(hooks).call(object, env)
    end

    def map
      Pipeline.new([[:map, mapper]]).insert_hooks(hooks).call(object, env)
    end

    def context
      {
        policy: policy,
        env: env,
        mapper_stack: []
      }.merge(slice_hash(options, :item_mapper))
    end
    memoize :context, freezer: :flat

    def env
      options.fetch(:env, {})
    end
    memoize :env, freezer: :noop

    # @return [Class]
    def format_class
      Format.by_accept_header(env['HTTP_ACCEPT']) {
        Format.by_name(options.fetch(:format) { default_format })
      }
    end
    memoize :format_class

    def steps
      [[ :map, mapper ],
       [ :format, formatter ],
       [ :primitivize, primitivizer],
       [ :serialize, serializer ]]
    end
    memoize :steps

    def mapper
      options.fetch(:mapper) do
        policy.derive_mapper_from_object(object)
      end.new(context)
    end
    memoize :mapper, freezer: :noop

    def formatter
      format_class.new(format_options_hash[format_name])
    end
    memoize :formatter

    def primitivizer
      proc do |input|
        if format_class.serializer.equal? :json
          primitivize.call(input)
        else
          input
        end
      end
    end
    memoize :primitivizer

    def serializer
      serializers.fetch(format_class.serializer)
    end
    memoize :serializer

    def hooks
      config.hooks + options.fetch(:hooks, [])
    end

  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
yaks-0.8.1 lib/yaks/runner.rb
yaks-0.8.0 lib/yaks/runner.rb
yaks-0.8.0.beta2 lib/yaks/runner.rb
yaks-0.8.0.beta1 lib/yaks/runner.rb
yaks-0.8.0.alpha lib/yaks/runner.rb