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'
23 # Provides a module which all other parsers should include.
26 content_type 'application/json'
33 def matches_kind(kind)
34 self.matches_field_value(:kind, kind)
37 def matches_fields(fields)
38 self.conditions << [:fields, fields]
41 def matches_field_value(field, value)
42 self.conditions << [:field_value, field, value]
51 # This method ensures that all parsers auto-register themselves.
52 def self.included(parser)
53 self.parsers << parser
54 parser.extend(Matcher)
58 @data = data.kind_of?(Hash) ? data : MultiJson.decode(data)
68 elsif self.respond_to?(:data)
71 raise TypeError, "Parser did not provide access to raw data."
77 # Matches a parser to the data.
79 for parser in self.parsers
81 for condition in (parser.conditions.sort_by { |c| c.size }).reverse
82 condition_type, *params = condition
86 if !data.has_key?(field)
87 conditions_met = false
93 if data[field] != value
94 conditions_met = false
98 raise ArgumentError, "Unknown condition type: #{condition_type}"
100 break if !conditions_met
110 data = json.kind_of?(Hash) ? json : MultiJson.decode(json)
111 parser = self.match(data)
113 return parser.new(data)