Module: AutoParse

Defined in:
lib/autoparse.rb,
lib/autoparse/version.rb,
lib/autoparse/instance.rb,
lib/autoparse/inflection.rb

Defined Under Namespace

Modules: VERSION Classes: Instance

Constant Summary collapse

EMPTY_SCHEMA =

The empty schema accepts all JSON.

Instance
INFLECTOR =
Extlib::Inflection

Class Method Summary collapse

Class Method Details

.export(value, schema_class, type = nil) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/autoparse.rb', line 169

def self.export(value, schema_class, type=nil)
  type = schema_class.data['type'] if type == nil
  case type
  when 'string'
    AutoParse.export_string(value, schema_class)
  when 'boolean'
    AutoParse.export_boolean(value, schema_class)
  when 'integer'
    AutoParse.export_integer(value, schema_class)
  when 'number'
    AutoParse.export_number(value, schema_class)
  when 'array'
    AutoParse.export_array(value, schema_class)
  when 'object'
    AutoParse.export_object(value, schema_class)
  when 'null'
    nil
  when Array
    AutoParse.export_union(value, schema_class)
  else
    AutoParse.export_any(value, schema_class)
  end
end

.export_any(value, schema_class) ⇒ Object



372
373
374
# File 'lib/autoparse.rb', line 372

def self.export_any(value, schema_class)
  value
end

.export_array(value, schema_class) ⇒ Object



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/autoparse.rb', line 317

def self.export_array(value, schema_class)
  if value == nil
    value
  elsif value.respond_to?(:to_ary)
    value = value.to_ary.dup
    items_data = schema_class.data['items']
    items_schema = AutoParse.generate(items_data, :parent => schema_class)
    if items_schema.data['$ref']
      # Dereference the schema if necessary.
      items_schema = items_schema.dereference
    end
    value.map! do |item|
      AutoParse.export(item, items_schema)
    end
    value
  else
    raise TypeError, "Expected Array, got #{value.class}."
  end
end

.export_boolean(value, schema_class) ⇒ Object



253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/autoparse.rb', line 253

def self.export_boolean(value, schema_class)
  case value.to_s.downcase
  when 'true', 'yes', 'y', 'on', '1'
    true
  when 'false', 'no', 'n', 'off', '0'
    false
  when 'nil', 'null', 'undefined'
    nil
  else
    raise TypeError, "Expected boolean, got #{value.class}."
  end
end

.export_integer(value, schema_class) ⇒ Object



290
291
292
293
294
295
296
# File 'lib/autoparse.rb', line 290

def self.export_integer(value, schema_class)
  if value == nil
    value
  else
    Integer(value)
  end
end

.export_number(value, schema_class) ⇒ Object



274
275
276
277
278
279
280
# File 'lib/autoparse.rb', line 274

def self.export_number(value, schema_class)
  if value == nil
    value
  else
    Float(value)
  end
end

.export_object(value, schema_class) ⇒ Object



341
342
343
344
345
346
347
348
349
350
351
352
# File 'lib/autoparse.rb', line 341

def self.export_object(value, schema_class)
  # FIXME: Every field must be exported as well.
  if value.nil?
    nil
  elsif value.respond_to?(:to_hash)
    value.to_hash
  elsif value.respond_to?(:to_json)
    ::JSON.parse(value.to_json)
  else
    raise TypeError, "Expected Hash, got #{value.class}."
  end
end

.export_string(value, schema_class) ⇒ Object



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/autoparse.rb', line 212

def self.export_string(value, schema_class)
  format = schema_class.data['format']
  if format == 'byte'
    Base64.encode64(value)
  elsif format == 'date-time'
    if value.respond_to?(:to_str)
      value = Time.parse(value.to_str)
    elsif !value.respond_to?(:xmlschema)
      raise TypeError,
        "Could not obtain RFC 3339 timestamp from #{value.class}."
    end
    value.xmlschema
  elsif format == 'url'
    # This effectively does limited URI validation.
    Addressable::URI.parse(value).to_str
  elsif format =~ /^u?int(32|64)$/
    value.to_s
  elsif value.respond_to?(:to_str)
    value.to_str
  elsif value.kind_of?(Symbol)
    value.to_s
  else
    raise TypeError,
      "Expected String or Symbol, got #{value.class}."
  end
end

.export_union(value, schema_class) ⇒ Object



361
362
363
364
365
366
# File 'lib/autoparse.rb', line 361

def self.export_union(value, schema_class)
  export_type = match_type(
    value, schema_class.data['type'], schema_class
  )
  AutoParse.export(value, schema_class, export_type)
end

.generate(schema_data, options = {}) ⇒ Object



24
25
26
27
28
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/autoparse.rb', line 24

def self.generate(schema_data, options={})
  uri = options[:uri]
  parent = options[:parent]
  if schema_data["extends"]
    super_uri = uri + Addressable::URI.parse(schema_data["extends"])
    super_schema = self.schemas[super_uri]
    if super_schema == nil
      raise ArgumentError,
        "Could not find schema to extend: #{schema_data["extends"]} " +
        "Parent schema must be parsed before child schema."
    end
  else
    super_schema = Instance
  end
  schema = Class.new(super_schema) do
    @uri = Addressable::URI.parse(uri)
    @uri.normalize! if @uri != nil
    @schema_data = schema_data
    if !self.uri && parent
      @uri = parent.uri
    end

    def self.additional_properties_schema
      # Override the superclass implementation so we're not always returning
      # the empty schema.
      if @additional_properties_schema.data['$ref']
        # Dereference the schema if necessary.
        @additional_properties_schema =
          @additional_properties_schema.dereference
      end
      return @additional_properties_schema
    end

    (@schema_data['properties'] || []).each do |(k, v)|
      property_key, property_schema = k, v
      property_name = INFLECTOR.underscore(property_key).gsub("-", "_")
      property_super_schema = super_schema.properties[property_key]
      if property_super_schema
        # TODO: Not sure if this should be a recursive merge or not...

        # TODO: Might need to raise an error if a schema is extended in
        # a way that violates the requirement that all child instances also
        # validate against the parent schema.
        property_schema = property_super_schema.data.merge(property_schema)
      end

      # If the schema has no ID, it inherits the ID from the parent schema.
      property_schema_class =
        AutoParse.generate(property_schema, :parent => self)

      self.properties[property_key] = property_schema_class
      self.keys[property_name] = property_key

      define_method(property_name) do
        __get__(property_name)
      end
      define_method(property_name + '=') do |value|
        __set__(property_name, value)
      end
    end

    if schema_data['additionalProperties'] == true ||
        schema_data['additionalProperties'] == nil
      # Schema-less unknown properties are allowed.
      @additional_properties_schema = EMPTY_SCHEMA
    elsif schema_data['additionalProperties']
      # Unknown properties follow the supplied schema.
      ap_schema = AutoParse.generate(
        schema_data['additionalProperties'], :parent => self
      )
      @additional_properties_schema = ap_schema
    else
      @additional_properties_schema = nil
    end

    define_method('method_missing') do |method, *params, &block|
      # We need to convert from Ruby calling style to JavaScript calling
      # style. If this fails, attempt to use JavaScript calling style
      # directly.

      # We can't modify the method in-place because this affects the call
      # to super.
      stripped_method = method.to_s
      assignment = false
      if stripped_method[-1..-1] == '='
        assignment = true
        stripped_method[-1..-1] = ''
      end
      key = INFLECTOR.camelize(stripped_method)
      key[0..0] = key[0..0].downcase
      if @data[key] != nil
        # Data found
      elsif @data[stripped_method] != nil
        # Data found
        key = stripped_method
      else
        # Method not found.
        super(method, *params, &block)
      end
      # If additionalProperties is simply set to true, no parsing takes
      # place and all values are treated as 'any'.
      if assignment
        new_value = params[0]
        self.__set__(key, new_value)
      else
        self.__get__(key)
      end
    end

    if schema_data['dependencies']
      for dependency_key, dependency_data in schema_data['dependencies']
        self.property_dependencies[dependency_key] = dependency_data
      end
    end
  end

  # Register the new schema.
  self.schemas[schema.uri] = schema
  return schema
end

.import(value, schema_class, type = nil) ⇒ Object



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/autoparse.rb', line 145

def self.import(value, schema_class, type=nil)
  type = schema_class.data['type'] if type == nil
  case type
  when 'string'
    return AutoParse.import_string(value, schema_class)
  when 'boolean'
    return AutoParse.import_boolean(value, schema_class)
  when 'integer'
    return AutoParse.import_integer(value, schema_class)
  when 'number'
    return AutoParse.import_number(value, schema_class)
  when 'array'
    return AutoParse.import_array(value, schema_class)
  when 'object'
    return AutoParse.import_object(value, schema_class)
  when 'null'
    return nil
  when Array
    return AutoParse.import_union(value, schema_class)
  else
    return AutoParse.import_any(value, schema_class)
  end
end

.import_any(value, schema_class) ⇒ Object



368
369
370
# File 'lib/autoparse.rb', line 368

def self.import_any(value, schema_class)
  value
end

.import_array(value, schema_class) ⇒ Object



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/autoparse.rb', line 298

def self.import_array(value, schema_class)
  value = (if value != nil && !value.respond_to?(:to_ary)
    raise TypeError,
      "Expected Array, got #{value.class}."
  else
    (value || []).to_ary.dup
  end)
  items_data = schema_class.data['items']
  items_schema = AutoParse.generate(items_data, :parent => schema_class)
  if items_schema.data['$ref']
    # Dereference the schema if necessary.
    items_schema = items_schema.dereference
  end
  value.map! do |item|
    AutoParse.import(item, items_schema)
  end
  value
end

.import_boolean(value, schema_class) ⇒ Object



239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/autoparse.rb', line 239

def self.import_boolean(value, schema_class)
  case value.to_s.downcase
  when 'true', 'yes', 'y', 'on', '1'
    true
  when 'false', 'no', 'n', 'off', '0'
    false
  when 'nil', 'null', 'undefined'
    nil
  else
    raise TypeError,
      "Expected boolean, got #{value.class}."
  end
end

.import_integer(value, schema_class) ⇒ Object



282
283
284
285
286
287
288
# File 'lib/autoparse.rb', line 282

def self.import_integer(value, schema_class)
  if value == nil
    value
  else
    Integer(value)
  end
end

.import_number(value, schema_class) ⇒ Object



266
267
268
269
270
271
272
# File 'lib/autoparse.rb', line 266

def self.import_number(value, schema_class)
  if value == nil
    value
  else
    Float(value)
  end
end

.import_object(value, schema_class) ⇒ Object



337
338
339
# File 'lib/autoparse.rb', line 337

def self.import_object(value, schema_class)
  value ? schema_class.new(value) : nil
end

.import_string(value, schema_class) ⇒ Object



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/autoparse.rb', line 193

def self.import_string(value, schema_class)
  if value != nil
    format = schema_class.data['format']
    if format == 'byte'
      Base64.decode64(value)
    elsif format == 'date-time'
      Time.parse(value)
    elsif format == 'url'
      Addressable::URI.parse(value)
    elsif format =~ /^u?int(32|64)$/
      value.to_i
    else
      value
    end
  else
    nil
  end
end

.import_union(value, schema_class) ⇒ Object



354
355
356
357
358
359
# File 'lib/autoparse.rb', line 354

def self.import_union(value, schema_class)
  import_type = match_type(
    value, schema_class.data['type'], schema_class
  )
  AutoParse.import(value, schema_class, import_type)
end

.match_type(value, union, parent = nil) ⇒ Object

Given a value and a union of types, selects the type which is the best match for the given value. More than one type may match the value, in which case, the first type in the union will be returned.



380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'lib/autoparse.rb', line 380

def self.match_type(value, union, parent=nil)
  possible_types = [union].flatten.compact
  # Strict pass
  for type in possible_types
    # We import as the first type in the list that validates.
    case type
    when 'string'
      return 'string' if value.kind_of?(String)
    when 'boolean'
      return 'boolean' if value == true or value == false
    when 'integer'
      return 'integer' if value.kind_of?(Integer)
    when 'number'
      return 'number' if value.kind_of?(Numeric)
    when 'array'
      return 'array' if value.kind_of?(Array)
    when 'object'
      return 'object' if value.kind_of?(Hash) || value.kind_of?(Instance)
    when 'null'
      return 'null' if value.nil?
    when Hash
      # Schema embedded directly.
      schema_class = AutoParse.generate(type, :parent => parent)
      if type['$ref']
        schema_class = schema_class.dereference
      end
      return schema_class if schema_class.new(value).valid?
    end
  end
  # Lenient pass
  for type in possible_types
    # We import as the first type in the list that validates.
    case type
    when 'string'
      return 'string' if value.respond_to?(:to_str) || value.kind_of?(Symbol)
    when 'boolean'
      if ['true', 'yes', 'y', 'on', '1',
          'false', 'no', 'n', 'off', '0'].include?(value.to_s.downcase)
        return 'boolean'
      end
    when 'integer'
      return 'integer' if value.to_i != 0 || value == "0"
    when 'number'
      return 'number' if value.to_f != 0.0 || value == "0" || value == "0.0"
    when 'array'
      return 'array' if value.respond_to?(:to_ary)
    when 'object'
      if value.respond_to?(:to_hash) || value.respond_to?(:to_json)
        return 'object'
      end
    when 'any'
      return 'any'
    end
  end
  return nil
end

.schemasObject



20
21
22
# File 'lib/autoparse.rb', line 20

def self.schemas
  @schemas ||= {}
end