Class: Primalize::Single::Object
- Inherits:
-
Object
- Object
- Primalize::Single::Object
- Defined in:
- lib/primalize/single.rb
Instance Method Summary collapse
- #===(value) ⇒ Object
- #coerce(hash) ⇒ Object
-
#initialize(types, &coercion) ⇒ Object
constructor
A new instance of Object.
- #inspect ⇒ Object
Constructor Details
#initialize(types, &coercion) ⇒ Object
Returns a new instance of Object.
269 270 271 272 |
# File 'lib/primalize/single.rb', line 269 def initialize types, &coercion @types = types @coercion = coercion end |
Instance Method Details
#===(value) ⇒ Object
274 275 276 277 278 279 280 |
# File 'lib/primalize/single.rb', line 274 def === value return false unless ::Hash === value @types.all? do |attr, type| type === value[attr] end end |
#coerce(hash) ⇒ Object
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 |
# File 'lib/primalize/single.rb', line 282 def coerce hash if @coercion return @coercion.call(hash) end if hash.respond_to? :map hash.each_with_object({}) do |(key, value), h| _, type = @types.find { |_, type| type === value } h[key] = if type.respond_to? :coerce type.coerce(value) else value end end else hash end end |
#inspect ⇒ Object
302 303 304 |
# File 'lib/primalize/single.rb', line 302 def inspect "object(#{@types.map { |attr, type| "#{attr}: #{type.inspect}" }.join(', ')})" end |