Class: Traverse

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/traverse.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(json) ⇒ Traverse

Returns a new instance of Traverse.



14
15
16
# File 'lib/traverse.rb', line 14

def initialize json
  @json = json
end

Instance Attribute Details

#jsonObject (readonly)

Returns the value of attribute json.



4
5
6
# File 'lib/traverse.rb', line 4

def json
  @json
end

Instance Method Details

#[](value) ⇒ Object

TODO clean this crap up



29
30
31
32
33
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
# File 'lib/traverse.rb', line 29

def [] value
  value = value.to_s
  if values = value.split("/") and values.size > 1
    str = values.map { |v| "['#{v}']" }.join
    code = "self#{str}"
    return eval(code)
  end
  result = 
    if @json.class == Array
      @json.find do |key| 
        if key.class == Array
          if key.first.class == Array
            if key.first.first == "$"
              key.first.last == value
            end
          elsif key.first.class == String
            key.first == value
          end
        end
      end
    else
      @json[value] || @json["@#{value}"]
    end
  if result
    if result.class == Hash
      result = result["$"] || result
    end
  end
  if result.class == Hash || result.class == Array
    result = Traverse.new(result)
  else
    result
  end
  return result if result
  return Traverse.new([])
end

#blank?Boolean Also known as: empty?

Returns:

  • (Boolean)


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

def blank?
  size == 0
end

#eachObject



6
7
8
# File 'lib/traverse.rb', line 6

def each
  @json.each { |j| yield Traverse.new(j) }
end

#multiple?Boolean

Returns:

  • (Boolean)


10
11
12
# File 'lib/traverse.rb', line 10

def multiple?
  @json.class == Array
end

#sizeObject



18
19
20
# File 'lib/traverse.rb', line 18

def size
  @json.size
end