Class: Attributor::Hash

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Container, Enumerable
Defined in:
lib/attributor/types/hash.rb

Direct Known Subclasses

Model

Constant Summary collapse

MAX_EXAMPLE_DEPTH =
5
CIRCULAR_REFERENCE_MARKER =
'...'.freeze

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Container

included

Constructor Details

#initialize(contents = {}) ⇒ Hash

Returns a new instance of Hash.



394
395
396
397
398
399
# File 'lib/attributor/types/hash.rb', line 394

def initialize(contents={})
  @validating = false
  @dumping = false

  @contents = contents
end

Class Attribute Details

.extra_keysObject

Returns the value of attribute extra_keys.



16
17
18
# File 'lib/attributor/types/hash.rb', line 16

def extra_keys
  @extra_keys
end

.insensitive_mapObject (readonly)

Returns the value of attribute insensitive_map.



15
16
17
# File 'lib/attributor/types/hash.rb', line 15

def insensitive_map
  @insensitive_map
end

.key_attributeObject (readonly)

Returns the value of attribute key_attribute.



14
15
16
# File 'lib/attributor/types/hash.rb', line 14

def key_attribute
  @key_attribute
end

.key_typeObject

Returns the value of attribute key_type.



12
13
14
# File 'lib/attributor/types/hash.rb', line 12

def key_type
  @key_type
end

.optionsObject (readonly)

Returns the value of attribute options.



12
13
14
# File 'lib/attributor/types/hash.rb', line 12

def options
  @options
end

.value_attributeObject (readonly)

Returns the value of attribute value_attribute.



13
14
15
# File 'lib/attributor/types/hash.rb', line 13

def value_attribute
  @value_attribute
end

.value_typeObject

Returns the value of attribute value_type.



12
13
14
# File 'lib/attributor/types/hash.rb', line 12

def value_type
  @value_type
end

Instance Attribute Details

#contentsObject (readonly)

TODO: Think about the format of the subcontexts to use: let’s use .at(key.to_s)



379
380
381
# File 'lib/attributor/types/hash.rb', line 379

def contents
  @contents
end

#dumpingObject (readonly)

Returns the value of attribute dumping.



392
393
394
# File 'lib/attributor/types/hash.rb', line 392

def dumping
  @dumping
end

#validatingObject (readonly)

Returns the value of attribute validating.



392
393
394
# File 'lib/attributor/types/hash.rb', line 392

def validating
  @validating
end

Class Method Details

.attributes(**options, &key_spec) ⇒ Object



58
59
60
# File 'lib/attributor/types/hash.rb', line 58

def self.attributes(**options, &key_spec)
  self.keys(options, &key_spec)
end

.check_option!(name, definition) ⇒ Object



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

def self.check_option!(name, definition)
  case name
  when :reference
    :ok # FIXME ... actually do something smart
  when :dsl_compiler
    :ok
  when :case_insensitive_load
    unless self.key_type <= String
      raise Attributor::AttributorException, ":case_insensitive_load may not be used with keys of type #{self.key_type.name}"
    end
    :ok
  when :allow_extra
    :ok
  else
    :unknown
  end
end

.construct(constructor_block, **options) ⇒ Object



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/attributor/types/hash.rb', line 115

def self.construct(constructor_block, **options)
  return self if constructor_block.nil?

  unless @concrete
    return self.of(key:self.key_type, value: self.value_type)
    .construct(constructor_block,**options)
  end

  if options[:case_insensitive_load] && !(self.key_type <= String)
    raise Attributor::AttributorException.new(":case_insensitive_load may not be used with keys of type #{self.key_type.name}")
  end

  self.keys(options, &constructor_block)
  self
end

.constructable?Boolean

Returns:



110
111
112
# File 'lib/attributor/types/hash.rb', line 110

def self.constructable?
  true
end

.definitionObject



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/attributor/types/hash.rb', line 72

def self.definition
  opts = {
    :key_type => @key_type,
    :value_type => @value_type
  }.merge(@options)

  blocks = @saved_blocks.shift(@saved_blocks.size)
  compiler = dsl_class.new(self, opts)
  compiler.parse(*blocks)

  @insensitive_map = self.keys.keys.each_with_object({}) do |k, map|
    map[k.downcase] = k
  end

  compiler
end

.describe(shallow = false) ⇒ Object



356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/attributor/types/hash.rb', line 356

def self.describe(shallow=false)
  hash = super

  if key_type
    hash[:key] = {type: key_type.describe}
  end

  if self.keys.any?
    # Spit keys if it's the root or if it's an anonymous structures
    if ( !shallow || self.name == nil) && self.keys.any?
      # FIXME: change to :keys when the praxis doc browser supports displaying those. or josep's demo is over.
      hash[:keys] = self.keys.each_with_object({}) do |(sub_name, sub_attribute), sub_attributes|
        sub_attributes[sub_name] = sub_attribute.describe(true)
      end
    end
  else
    hash[:value] = {type: value_type.describe(true)}
  end

  hash
end

.dsl_classObject



89
90
91
# File 'lib/attributor/types/hash.rb', line 89

def self.dsl_class
  @options[:dsl_compiler] || DSLCompiler
end

.dump(value, **opts) ⇒ Object



187
188
189
190
# File 'lib/attributor/types/hash.rb', line 187

def self.dump(value, **opts)
  self.load(value).
    dump(**opts)
end

.example(context = nil, **values) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/attributor/types/hash.rb', line 158

def self.example(context=nil, **values)
  if (key_type == Object && value_type == Object && self.keys.empty?)
    return self.new 
  end

  context ||= ["#{Hash}-#{rand(10000000)}"]
  context = Array(context)

  if self.keys.any?
    result = self.new
    result.extend(ExampleMixin)

    result.lazy_attributes = self.example_contents(context, result, values)
  else
    hash = ::Hash.new

    (rand(3) + 1).times do |i|
      example_key = key_type.example(context + ["at(#{i})"])
      subcontext = context + ["at(#{example_key})"]
      hash[example_key] = value_type.example(subcontext)
    end

    result = self.new(hash)
  end

  result
end

.example_contents(context, parent, **values) ⇒ Object



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/attributor/types/hash.rb', line 132

def self.example_contents(context, parent, **values)
  hash = ::Hash.new
  example_depth = context.size

  self.keys.each do |sub_attribute_name, sub_attribute|
    if sub_attribute.attributes
      # TODO: add option to raise an exception in this case?
      next if example_depth > MAX_EXAMPLE_DEPTH
    end

    sub_context = self.generate_subcontext(context,sub_attribute_name)
    block = Proc.new do
      value = values.fetch(sub_attribute_name) do
        sub_attribute.example(sub_context, parent: parent)
      end

      sub_attribute.load(value,sub_context)
    end


    hash[sub_attribute_name] = block
  end

  hash
end

.from_hash(object, context, recurse: false) ⇒ Object



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/attributor/types/hash.rb', line 315

def self.from_hash(object,context, recurse: false)
  hash = self.new

  # if the hash definition includes named extra keys, initialize
  # its value from the object in case it provides some already.
  # this is to ensure it exists when we handle any extra keys
  # that may exist in the object later
  if self.extra_keys
    sub_context = self.generate_subcontext(context,self.extra_keys)
    v = object.fetch(self.extra_keys, {})
    hash.set(self.extra_keys, v, context: sub_context, recurse: recurse)
  end

  object.each do |k,v|
    next if k == self.extra_keys

    sub_context = self.generate_subcontext(Attributor::DEFAULT_ROOT_CONTEXT,k)
    hash.set(k, v, context: sub_context, recurse: recurse)
  end

  # handle default values for missing keys
  self.keys.each do |key_name, attribute|
    next if hash.key?(key_name)
    sub_context = self.generate_subcontext(context,key_name)
    hash[key_name] = attribute.load(nil, sub_context, recurse: recurse)
  end

  hash
end

.generate_subcontext(context, key_name) ⇒ Object



246
247
248
# File 'lib/attributor/types/hash.rb', line 246

def self.generate_subcontext(context, key_name)
  context + ["key(#{key_name.inspect})"]
end

.inherited(klass) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/attributor/types/hash.rb', line 43

def self.inherited(klass)
  k = self.key_type
  v = self.value_type

  klass.instance_eval do
    @saved_blocks = []
    @options = {allow_extra: false}
    @keys = {}
    @key_type = k
    @value_type = v
    @key_attribute = Attribute.new(@key_type)
    @value_attribute = Attribute.new(@value_type)
  end
end

.keys(**options, &key_spec) ⇒ Object



62
63
64
65
66
67
68
69
70
# File 'lib/attributor/types/hash.rb', line 62

def self.keys(**options, &key_spec)
  if block_given?
    @saved_blocks << key_spec
    @options.merge!(options)
  elsif @saved_blocks.any?
    self.definition
  end
  @keys
end

.load(value, context = Attributor::DEFAULT_ROOT_CONTEXT, recurse: false, **options) ⇒ 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
238
239
240
241
242
243
244
# File 'lib/attributor/types/hash.rb', line 212

def self.load(value,context=Attributor::DEFAULT_ROOT_CONTEXT, recurse: false, **options)
  context = Array(context)

  if value.nil?
    if recurse
      loaded_value = {}
    else
      return nil
    end
  elsif value.is_a?(self)
    return value
  elsif value.kind_of?(Attributor::Hash)
    if (value.keys - self.attributes.keys).any?
      raise Attributor::IncompatibleTypeError, context: context, value_type: value.class, type: self
    end

    loaded_value = value.contents
  elsif value.is_a?(::Hash)
    loaded_value = value
  elsif value.is_a?(::String)
    loaded_value = decode_json(value,context)
  else
    raise Attributor::IncompatibleTypeError, context: context, value_type: value.class, type: self
  end

  return self.from_hash(loaded_value,context, recurse: recurse) if self.keys.any?
  return self.new(loaded_value) if (key_type == Object && value_type == Object)

  loaded_value.each_with_object(self.new) do| (k, v), obj |
    obj[self.key_type.load(k,context)] = self.value_type.load(v,context)
  end

end

.native_typeObject



93
94
95
# File 'lib/attributor/types/hash.rb', line 93

def self.native_type
  self
end

.of(key: @key_type, value: @value_type) ⇒ Object

Examples:

Hash.of(key: String, value: Integer)



102
103
104
105
106
107
108
# File 'lib/attributor/types/hash.rb', line 102

def self.of(key: @key_type, value: @value_type)
  Class.new(self) do
    self.key_type = key
    self.value_type = value
    @keys = {}
  end
end

.valid_type?(type) ⇒ Boolean

Returns:



97
98
99
# File 'lib/attributor/types/hash.rb', line 97

def self.valid_type?(type)
  type.kind_of?(self) || type.kind_of?(::Hash)
end

.validate(object, context = Attributor::DEFAULT_ROOT_CONTEXT, _attribute) ⇒ Object



346
347
348
349
350
351
352
353
354
# File 'lib/attributor/types/hash.rb', line 346

def self.validate(object,context=Attributor::DEFAULT_ROOT_CONTEXT,_attribute)
  context = [context] if context.is_a? ::String

  unless object.kind_of?(self)
    raise ArgumentError, "#{self.name} can not validate object of type #{object.class.name} for #{Attributor.humanize_context(context)}."
  end

  object.validate(context)
end

Instance Method Details

#==(other) ⇒ Object



418
419
420
# File 'lib/attributor/types/hash.rb', line 418

def ==(other)
  contents == other || (other.respond_to?(:contents) ? contents == other.contents : false)
end

#dump(**opts) ⇒ Object



461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
# File 'lib/attributor/types/hash.rb', line 461

def dump(**opts)
  return CIRCULAR_REFERENCE_MARKER if @dumping

  @dumping = true

  @contents.each_with_object({}) do |(k,v),hash|
    k = self.key_attribute.dump(k,opts)

    if (attribute_for_value = self.class.keys[k])
      v = attribute_for_value.dump(v,opts)
    else
      v = self.value_attribute.dump(v,opts)
    end

    hash[k] = v
  end
ensure
  @dumping = false
end

#generate_subcontext(context, key_name) ⇒ Object



250
251
252
# File 'lib/attributor/types/hash.rb', line 250

def generate_subcontext(context, key_name)
  self.class.generate_subcontext(context,key_name)
end

#get(key, context: self.generate_subcontext(Attributor::DEFAULT_ROOT_CONTEXT,key)) ⇒ Object



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/attributor/types/hash.rb', line 254

def get(key, context: self.generate_subcontext(Attributor::DEFAULT_ROOT_CONTEXT,key))
  key = self.class.key_attribute.load(key, context)
  
  value = @contents[key]

  if (attribute = self.class.keys[key])
    return self[key] = attribute.load(value, context)
  end

  if self.class.options[:case_insensitive_load]
    key = self.class.insensitive_map[key.downcase]
    return self.get(key, context: context)
  end

  if self.class.options[:allow_extra]
    if self.class.extra_keys.nil?
      return @contents[key] = self.class.value_attribute.load(value, context)
    else
      extra_keys_key = self.class.extra_keys

      if @contents.key? extra_keys_key
        return @contents[extra_keys_key].get(key, context: context)
      end

    end
  end

  raise AttributorException, "Unknown key received: #{key.inspect} for #{Attributor.humanize_context(context)}"
end

#key_attributeObject



409
410
411
# File 'lib/attributor/types/hash.rb', line 409

def key_attribute
  self.class.key_attribute
end

#key_typeObject



401
402
403
# File 'lib/attributor/types/hash.rb', line 401

def key_type
  self.class.key_type
end

#set(key, value, context: self.generate_subcontext(Attributor::DEFAULT_ROOT_CONTEXT,key), recurse: false) ⇒ Object



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/attributor/types/hash.rb', line 285

def set(key, value, context: self.generate_subcontext(Attributor::DEFAULT_ROOT_CONTEXT,key), recurse: false)
  key = self.class.key_attribute.load(key, context)

  if (attribute = self.class.keys[key])
    return self[key] = attribute.load(value, context, recurse: recurse)
  end

  if self.class.options[:case_insensitive_load]
    key = self.class.insensitive_map[key.downcase]
    return self.set(key, value, context: context)
  end

  if self.class.options[:allow_extra]
    if self.class.extra_keys.nil?
      return self[key] = self.class.value_attribute.load(value, context)
    else
      extra_keys_key = self.class.extra_keys

      unless @contents.key? extra_keys_key
        extra_keys_value = self.class.keys[extra_keys_key].load({})
        @contents[extra_keys_key] = extra_keys_value
      end

      return self[extra_keys_key].set(key, value, context: context)
    end
  end

  raise AttributorException, "Unknown key received: #{key.inspect} while loading #{Attributor.humanize_context(context)}"
end

#validate(context = Attributor::DEFAULT_ROOT_CONTEXT) ⇒ Object



422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# File 'lib/attributor/types/hash.rb', line 422

def validate(context=Attributor::DEFAULT_ROOT_CONTEXT)
  context = [context] if context.is_a? ::String

  if self.class.keys.any?
    extra_keys = @contents.keys - self.class.keys.keys
    if extra_keys.any? && !self.class.options[:allow_extra]
      return extra_keys.collect do |k|
        "#{Attributor.humanize_context(context)} can not have key: #{k.inspect}"
      end
    end

    self.class.keys.each_with_object(Array.new) do |(key, attribute), errors|
      sub_context = self.class.generate_subcontext(context,key)

      value = @contents[key]

      if value.respond_to?(:validating) # really, it's a thing with sub-attributes
        next if value.validating
      end

      errors.push *attribute.validate(value, sub_context)
    end
  else
    @contents.each_with_object(Array.new) do |(key, value), errors|
      # FIXME: the sub contexts and error messages don't really make sense here
      unless key_type == Attributor::Object
        sub_context = context + ["key(#{key.inspect})"]
        errors.push *key_attribute.validate(key, sub_context)
      end

      unless value_type == Attributor::Object
        sub_context = context + ["value(#{value.inspect})"]
        errors.push *value_attribute.validate(value, sub_context)
      end
    end
  end
end

#value_attributeObject



413
414
415
# File 'lib/attributor/types/hash.rb', line 413

def value_attribute
  self.class.value_attribute
end

#value_typeObject



405
406
407
# File 'lib/attributor/types/hash.rb', line 405

def value_type
  self.class.value_type
end