Class: CMDx::CoercionRegistry
- Inherits:
-
Object
- Object
- CMDx::CoercionRegistry
- Defined in:
- lib/cmdx/coercion_registry.rb
Overview
Registry for managing type coercion handlers.
Provides a centralized way to register, deregister, and execute type coercions for various data types including arrays, numbers, dates, and other primitives.
Instance Attribute Summary collapse
-
#registry ⇒ Hash{Symbol => Class}
(also: #to_h)
readonly
Returns the internal registry mapping coercion types to handler classes.
Instance Method Summary collapse
-
#coerce(type, task, value, options = {}) ⇒ Object
Coerce a value to the specified type using the registered handler.
-
#deregister(name) ⇒ CoercionRegistry
Remove a coercion handler for a type.
-
#dup ⇒ CoercionRegistry
Create a duplicate of this registry.
-
#initialize(registry = nil) ⇒ CoercionRegistry
constructor
Initialize a new coercion registry.
-
#register(name, coercion) ⇒ CoercionRegistry
Register a new coercion handler for a type.
Constructor Details
#initialize(registry = nil) ⇒ CoercionRegistry
Initialize a new coercion registry.
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/cmdx/coercion_registry.rb', line 30 def initialize(registry = nil) @registry = registry || { array: Coercions::Array, big_decimal: Coercions::BigDecimal, boolean: Coercions::Boolean, complex: Coercions::Complex, date: Coercions::Date, datetime: Coercions::DateTime, float: Coercions::Float, hash: Coercions::Hash, integer: Coercions::Integer, rational: Coercions::Rational, string: Coercions::String, time: Coercions::Time } end |
Instance Attribute Details
#registry ⇒ Hash{Symbol => Class} (readonly) Also known as: to_h
Returns the internal registry mapping coercion types to handler classes.
18 19 20 |
# File 'lib/cmdx/coercion_registry.rb', line 18 def registry @registry end |
Instance Method Details
#coerce(type, task, value, options = {}) ⇒ Object
Coerce a value to the specified type using the registered handler.
109 110 111 112 113 |
# File 'lib/cmdx/coercion_registry.rb', line 109 def coerce(type, task, value, = {}) raise TypeError, "unknown coercion type #{type.inspect}" unless registry.key?(type) Utils::Call.invoke(task, registry[type], value, ) end |
#deregister(name) ⇒ CoercionRegistry
Remove a coercion handler for a type.
87 88 89 90 |
# File 'lib/cmdx/coercion_registry.rb', line 87 def deregister(name) registry.delete(name.to_sym) self end |
#dup ⇒ CoercionRegistry
Create a duplicate of this registry.
55 56 57 |
# File 'lib/cmdx/coercion_registry.rb', line 55 def dup self.class.new(registry.dup) end |
#register(name, coercion) ⇒ CoercionRegistry
Register a new coercion handler for a type.
71 72 73 74 |
# File 'lib/cmdx/coercion_registry.rb', line 71 def register(name, coercion) registry[name.to_sym] = coercion self end |