Sha256: a5511031247998936e7f82cabafd508e2237916437d57fcaefbaf73312e18c39

Contents?: true

Size: 952 Bytes

Versions: 8

Compression:

Stored size: 952 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, 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
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
yaks-0.7.7 lib/yaks/primitivize.rb
yaks-0.7.6 lib/yaks/primitivize.rb
yaks-0.7.5 lib/yaks/primitivize.rb
yaks-0.7.4 lib/yaks/primitivize.rb
yaks-0.7.3 lib/yaks/primitivize.rb
yaks-0.7.2 lib/yaks/primitivize.rb
yaks-0.7.1 lib/yaks/primitivize.rb
yaks-0.7.0 lib/yaks/primitivize.rb