Sha256: 79b303bcab51412af4684000563e4fe96e6629770c412109dadfc9fc465d90fc

Contents?: true

Size: 1.26 KB

Versions: 5

Compression:

Stored size: 1.26 KB

Contents

# frozen_string_literal: true

require 'delegate'
require 'time'
require 'peddler/structured_list'

module Peddler
  # @api private
  class Operation < SimpleDelegator
    CAPITAL_LETTERS = /[A-Z]/

    def initialize(action)
      super('Action' => action)
    end

    def structure!(*list_keys)
      list_key = list_keys.shift
      found_key = keys.find { |key| key.end_with?(list_key) }
      if found_key
        builder = StructuredList.new(found_key, *list_keys)
        vals = delete(found_key)
        update(builder.build(vals))
      end

      self
    end

    def store(key, val, parent: '')
      key = camelize(key) if key.is_a?(Symbol)
      key = "#{parent}.#{key}" unless parent.empty?

      val = val.iso8601 if val.respond_to?(:iso8601)
      val = val.to_h if val.is_a?(Struct)

      if val.is_a?(Hash)
        val.each { |keyval| store(*keyval, parent: key) }
      else
        __getobj__.store(key, val)
      end
    end

    def update(hsh)
      hsh.each { |key, val| store(key, val) }
      self
    end

    alias add update

    private

    def camelize(sym)
      return sym.to_s if sym =~ CAPITAL_LETTERS

      sym
        .to_s
        .split('_')
        .map { |token| token == 'sku' ? 'SKU' : token.capitalize }
        .join
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
peddler-2.0.0 lib/peddler/operation.rb
peddler-1.6.7 lib/peddler/operation.rb
peddler-1.6.6 lib/peddler/operation.rb
peddler-1.6.5 lib/peddler/operation.rb
peddler-1.6.4 lib/peddler/operation.rb