Class: Primalize::Single::Object

Inherits:
Object
  • Object
show all
Defined in:
lib/primalize/single.rb

Instance Method Summary collapse

Constructor Details

#initialize(types, &coercion) ⇒ Object

Returns a new instance of Object.



285
286
287
288
# File 'lib/primalize/single.rb', line 285

def initialize types, &coercion
  @types = types
  @coercion = coercion
end

Instance Method Details

#===(value) ⇒ Object



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

def === value
  return false unless ::Hash === value

  @types.all? do |attr, type|
    type === value[attr]
  end
end

#coerce(hash) ⇒ Object



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

def coerce hash
  if @coercion
    return @coercion.call(hash)
  end

  if hash.respond_to? :each_with_object
    hash.each_with_object({}) do |(key, value), h|
      type = @types[key]

      h[key] = if type.respond_to? :coerce
                 type.coerce(value)
               else
                 value
               end
    end
  else
    hash
  end
end

#inspectObject



318
319
320
# File 'lib/primalize/single.rb', line 318

def inspect
  "object(#{@types.map { |attr, type| "#{attr}: #{type.inspect}" }.join(', ')})"
end