Class: Outstream::Json::Collector

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

Instance Method Summary collapse

Constructor Details

#initialize(yielder) ⇒ Collector

Returns a new instance of Collector.



63
64
65
66
# File 'lib/outstream/json.rb', line 63

def initialize(yielder)
  @yielder = yielder
  @count = [0]
end

Instance Method Details

#add(objs, &block) ⇒ Object



81
82
83
84
85
86
87
88
# File 'lib/outstream/json.rb', line 81

def add(objs, &block)
  if block
    add_key objs
    add_object &block
  else
    add_to_object objs
  end
end

#add_array(a) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/outstream/json.rb', line 113

def add_array(a)
  begin
    write "["
    a.enum_for(:each).each_with_index {|v,i|
      write "," if i > 0
      add_value v
    }
  rescue
    raise
  ensure
    write "]"
  end
end

#add_key(key) ⇒ Object



95
96
97
98
99
100
# File 'lib/outstream/json.rb', line 95

def add_key(key)
  write "," if @count.last > 0
  write key.to_json
  write ":"
  @count[@count.size-1] += 1
end

#add_objectObject



101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/outstream/json.rb', line 101

def add_object
  begin
    write "{"
    @count.push 0
    return yield
  rescue
    raise
  ensure
    @count.pop
    write "}"
  end
end

#add_to_object(objs) ⇒ Object



89
90
91
92
93
94
# File 'lib/outstream/json.rb', line 89

def add_to_object(objs)
  objs.each_pair {|key,val|
    add_key key
    add_value val
  }
end

#add_value(value) ⇒ Object



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/outstream/json.rb', line 126

def add_value(value)
  if value.respond_to?:each_pair
    add_object { add_to_object value }
  elsif value.respond_to?:each
    add_array value
  elsif value.respond_to?:call
    begin
      add_value value.call
    rescue
      add_value nil
      raise
    end
  else
    write value.to_json
  end
end

#collect(&block) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
# File 'lib/outstream/json.rb', line 67

def collect(&block)
  add_object {
    receiver = Receiver.new self
    if block.arity == 1
      block[receiver]
    else
      (class << receiver; self; end).send(:define_method, :__call_block, &block)
      receiver.__call_block
    end
  }
end

#write(str) ⇒ Object



78
79
80
# File 'lib/outstream/json.rb', line 78

def write(str)
  @yielder << str
end