1 # Copyright 2010 Google Inc.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
17 require 'google/api_client/parser'
22 # Provides a module which all other parsers should include.
25 content_type 'application/json'
32 def matches_kind(kind)
33 self.matches_field_value(:kind, kind)
36 def matches_fields(fields)
37 self.conditions << [:fields, fields]
40 def matches_field_value(field, value)
41 self.conditions << [:field_value, field, value]
50 # This method ensures that all parsers auto-register themselves.
51 def self.included(parser)
52 self.parsers << parser
53 parser.extend(Matcher)
57 @data = data.kind_of?(Hash) ? data : ::JSON.parse(data)
67 elsif self.respond_to?(:data)
70 raise TypeError, "Parser did not provide access to raw data."
76 # Matches a parser to the data.
78 for parser in self.parsers
80 for condition in (parser.conditions.sort_by { |c| c.size }).reverse
81 condition_type, *params = condition
85 if !data.has_key?(field)
86 conditions_met = false
92 if data[field] != value
93 conditions_met = false
97 raise ArgumentError, "Unknown condition type: #{condition_type}"
99 break if !conditions_met
109 data = json.kind_of?(Hash) ? json : ::JSON.parse(json)
110 parser = self.match(data)
112 return parser.new(data)