class Yaks::Primitivize

Attributes

mappings[R]

Public Class Methods

create() click to toggle source
# File lib/yaks/primitivize.rb, line 23
def self.create
  new.tap do |p|
    p.map String, Numeric, true, false, nil do |object|
      object
    end

    p.map Symbol, URI do |object|
      object.to_s
    end

    p.map Hash do |object|
      object.to_enum.with_object({}) do |(key, value), output|
        output[call(key)] = call(value)
      end
    end

    p.map Enumerable do |object|
      object.map(&method(:call))
    end
  end
end
new() click to toggle source
# File lib/yaks/primitivize.rb, line 5
def initialize
  @mappings = {}
end

Public Instance Methods

call(object) click to toggle source
# File lib/yaks/primitivize.rb, line 9
def call(object)
  mappings.each do |pattern, block|
    # rubocop:disable Style/CaseEquality
    return instance_exec(object, &block) if pattern === object
  end
  raise PrimitivizeError, "don't know how to turn #{object.class} (#{object.inspect}) into a primitive"
end
map(*types, &block) click to toggle source
# File lib/yaks/primitivize.rb, line 17
def map(*types, &block)
  types.each do |type|
    @mappings = mappings.merge(type => block)
  end
end