Sha256: bfbfb8bdf33d8abd46a324079891ddcc637165a2f15c59e43958ca124c2ae7ff

Contents?: true

Size: 1.12 KB

Versions: 1

Compression:

Stored size: 1.12 KB

Contents

# frozen_string_literal: true

# Used internally by the KeyMapable concern.
class KeyMapable::Mapper
  attr_reader :subject, :structure

  def initialize(subject)
    @subject = subject
    @structure = {}
  end

  def key_value(key)
    @structure[key] = yield()
  end

  def key(name, &block)
    child_mapper = self.class.new(subject)
    child_mapper.instance_eval(&block)
    @structure[name] = child_mapper.resolve
  end

  def key_map(original_key, new_key, &block)
    original_subject = subject.public_send(original_key)
    if block_given?
      child_mapper = self.class.new(original_subject)
      child_mapper.instance_eval &block
      @structure[new_key] = child_mapper.resolve
    else
      @structure[new_key] = original_subject
    end
  end

  def array_key_map(original_key, new_key, &block)
    original_subject = subject.public_send(original_key)
    @structure[new_key] = original_subject.map do |item|
      child_mapper = self.class.new(item)
      child_mapper.instance_eval(&block)
      child_mapper.resolve
    end
  end

  def transform
    @structure = yield(@subject)
  end

  def resolve
    @structure
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
key_mapable-0.3.0 lib/key_mapable/mapper.rb