Sha256: 5cff36ff4c0c2f91c3776ba07fe4bca8ec1d2a650028dcd7392bd480fb0d525c

Contents?: true

Size: 947 Bytes

Versions: 2

Compression:

Stored size: 947 Bytes

Contents

module Yaks
  class Primitivize

    attr_reader :mappings

    def initialize
      @mappings = {}
    end

    def call(object)
      mappings.each do |pattern, block|
        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

    def map(*types, &blk)
      types.each do |type|
        mappings[type] = blk
      end
    end

    def self.create
      new.tap do |p|
        p.map String, Numeric, true, false, nil do |object|
          object
        end

        p.map Symbol 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
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
yaks-0.6.2 lib/yaks/primitivize.rb
yaks-0.6.1 lib/yaks/primitivize.rb