Module: RSchema::CoercionMapper
- Defined in:
- lib/rschema.rb
Class Method Summary collapse
- .coerce_hash(schema, value) ⇒ Object
- .postwalk(schema, value) ⇒ Object
- .prewalk(schema, value) ⇒ Object
- .try_convert(x) ⇒ Object
Class Method Details
.coerce_hash(schema, value) ⇒ Object
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 |
# File 'lib/rschema.rb', line 138 def self.coerce_hash(schema, value) symbol_keys = Set.new(schema.keys.select{ |k| k.is_a?(Symbol) }.map(&:to_s)) value.reduce({}) do |accum, (k, v)| # convert string keys to symbol keys, if needed if k.is_a?(String) && symbol_keys.include?(k) k = k.to_sym end # strip out keys that don't exist in the schema if schema.has_key?(k) || schema.has_key?(OptionalHashKey.new(k)) accum[k] = v end accum end end |
.postwalk(schema, value) ⇒ Object
128 129 130 |
# File 'lib/rschema.rb', line 128 def self.postwalk(schema, value) value end |
.prewalk(schema, value) ⇒ Object
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
# File 'lib/rschema.rb', line 106 def self.prewalk(schema, value) if schema == Integer && value.is_a?(String) try_convert(value) { Integer(value) } elsif schema == Float && value.is_a?(String) try_convert(value) { Float(value) } elsif schema == Float && value.is_a?(Integer) value.to_f elsif schema == Symbol && value.is_a?(String) value.to_sym elsif schema == String && value.is_a?(Symbol) value.to_s elsif schema == Array && value.is_a?(Set) value.to_a elsif (schema == Set || schema.is_a?(GenericSetSchema)) && value.is_a?(Array) Set.new(value) elsif(schema.is_a?(Hash) && value.is_a?(Hash)) coerce_hash(schema, value) else value end end |
.try_convert(x) ⇒ Object
132 133 134 135 136 |
# File 'lib/rschema.rb', line 132 def self.try_convert(x) yield x rescue x end |