Sha256: f76f38dc3c742f86af15edf496e0e23e38374d25b37589a5fedb57b167c55048

Contents?: true

Size: 956 Bytes

Versions: 3

Compression:

Stored size: 956 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 "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, TrueClass, FalseClass, NilClass, Numeric do |object|
          object
        end

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

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

        p.map Enumerable do |object|
          object.map(&method(:call)).to_a
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
yaks-0.4.1 lib/yaks/primitivize.rb
yaks-0.4.0 lib/yaks/primitivize.rb
yaks-0.4.0.rc1 lib/yaks/primitivize.rb