Class: Simplifier

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

Overview

Public: Reduce Ruby objects to a more primitive representation.

Defined Under Namespace

Classes: Circular, Unknown

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = nil) ⇒ Simplifier

Public: Create a new instance.



28
29
30
31
# File 'lib/simplifier.rb', line 28

def initialize(options = nil)
  @options = options || {}
  @symbols = Hash.new { |h, k| h[k] = k.to_s.freeze }
end

Instance Attribute Details

#optionsObject (readonly)

Public: Get a Hash of Symbol-keyed options.



22
23
24
# File 'lib/simplifier.rb', line 22

def options
  @options
end

#symbolsObject (readonly)

Internal: A Hash cache of String representations of Symbols.



25
26
27
# File 'lib/simplifier.rb', line 25

def symbols
  @symbols
end

Instance Method Details

#simplify(object) ⇒ Object

Internal.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/simplifier.rb', line 34

def simplify(object)
  case object
  when Array, Set
    object.map { |o| simplify o }

  when DateTime
    simplify object.to_time

  when Date
    object.iso8601

  when Hash
    {}.tap do |hash|
      object.each do |key, value|
        hash[simplify key] = simplify value
      end
    end

  when NilClass
    object

  when Numeric
    object

  when String
    return object if object.encoding == Encoding::BINARY

    object.encode Encoding::UTF_8,
      :invalid => :replace, :undef => :replace, :universal_newline => true

  when Symbol
    symbols[object]

  when Time
    object.utc.iso8601

  when TrueClass, FalseClass
    object

  else
    raise Unknown, object
  end
end