Class: Yaks::Primitivize

Inherits:
Object
  • Object
show all
Defined in:
lib/yaks/primitivize.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializePrimitivize

Returns a new instance of Primitivize.



5
6
7
# File 'lib/yaks/primitivize.rb', line 5

def initialize
  @mappings = {}
end

Instance Attribute Details

#mappingsObject (readonly)

Returns the value of attribute mappings.



3
4
5
# File 'lib/yaks/primitivize.rb', line 3

def mappings
  @mappings
end

Class Method Details

.createObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 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

Instance Method Details

#call(object) ⇒ Object

Raises:



9
10
11
12
13
14
15
# 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) ⇒ Object



17
18
19
20
21
# File 'lib/yaks/primitivize.rb', line 17

def map(*types, &block)
  types.each do |type|
    @mappings = mappings.merge(type => block)
  end
end