Module: Siren

Defined in:
lib/siren/parser.rb,
lib/siren.rb,
lib/siren/json.rb,
lib/siren/node.rb,
lib/siren/walker.rb,
lib/siren/reference.rb,
lib/siren/json_query.rb,
lib/siren/json_query_nodes.rb

Overview

Based on www.json.org/json_parse.js (public domain)

Defined Under Namespace

Modules: Json, JsonQuery, Node, Walker Classes: JsonParser, JsonQueryParser, Parser, Reference

Constant Summary collapse

VERSION =
'0.2.0'
TYPE_FIELD =
"type"
ID_FIELD =
"id"
REF_FIELD =
"$ref"

Class Method Summary collapse

Class Method Details

.compile_query(expression) ⇒ Object



70
71
72
73
74
# File 'lib/siren.rb', line 70

def self.compile_query(expression)
  @query_parser ||= JsonQueryParser.new
  @query_cache  ||= {}
  @query_cache[expression] ||= @query_parser.parse(expression)
end

.each(object, &block) ⇒ Object



23
24
25
26
27
28
29
30
# File 'lib/siren.rb', line 23

def self.each(object, &block)
  case object
  when Array      then object.each_with_index { |x,i| yield(i,x) }
  when Hash       then object.each { |k,v| yield(k,v) }
  when Enumerable then each(object.to_a, &block)
  else nil
  end
end

.parse(string, &block) ⇒ Object



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/siren.rb', line 32

def self.parse(string, &block)
  @json_parser ||= JsonParser.new
  Reference.flush!
  @symbols = {}
  
  result = @json_parser.parse(string).value rescue nil
  
  @json_parser.walk(result) do |holder, key, value|
    if Hash === value && value[REF_FIELD]
      value = Reference.new(value)
      value.on(:resolve) do |ref, root, symbols|
        holder[key] = ref.find(root, symbols, holder)
      end
    end
    value
  end
  
  @json_parser.walk(result) do |holder, key, value|
    if Hash === value
      id = value[ID_FIELD]
      value = Node.from_json(value)
      @symbols[id] = value
    end
    value
  end
  
  result = Node.from_json(result)
  
  Reference.resolve!(result, @symbols)
  @json_parser.walk(result, &block) if block_given?
  
  result
end

.query(expression, root) ⇒ Object



66
67
68
# File 'lib/siren.rb', line 66

def self.query(expression, root)
  compile_query(expression).value(root, @symbols || {})
end