Module: Hattr::HashBuilder
- Defined in:
- lib/hattr/hash_builder.rb
Constant Summary collapse
- ARRAY_TYPE_DEFAULT =
Array[String]
- HASH_TYPE_DEFAULT =
Hash[Symbol => String]
Class Method Summary collapse
- .array_typecast(value, model) ⇒ Object
- .generate(spec, raw) ⇒ Object
- .hash_typecast(value, model) ⇒ Object
- .primitive_typecast(value, type) ⇒ Object
- .string_to_array(str) ⇒ Object
- .string_to_hash(str) ⇒ Object
- .typecast(value, type) ⇒ Object
Class Method Details
.array_typecast(value, model) ⇒ Object
43 44 45 46 47 48 |
# File 'lib/hattr/hash_builder.rb', line 43 def array_typecast(value, model) val_type = model.first array = string_to_array(value) array.map { |elem| typecast(elem, val_type) } end |
.generate(spec, raw) ⇒ Object
9 10 11 12 13 14 |
# File 'lib/hattr/hash_builder.rb', line 9 def generate(spec, raw) opts = spec.delete(ClassMethods::OPTIONS_STORAGE_KEY) raw = raw.symbolize_keys unless opts[:string_keys] raw.each { |k, v| raw[k] = typecast(v, spec.fetch(k.to_sym, ClassMethods::ATTR_DEFAULTS)[:type]) } end |
.hash_typecast(value, model) ⇒ Object
35 36 37 38 39 40 41 |
# File 'lib/hattr/hash_builder.rb', line 35 def hash_typecast(value, model) key_type, val_type = model.flatten hash = string_to_hash(value) hash = key_type == Symbol ? hash.symbolize_keys : hash hash.each { |k, v| hash[k] = typecast(v, val_type) } end |
.primitive_typecast(value, type) ⇒ Object
24 25 26 27 28 29 30 31 32 33 |
# File 'lib/hattr/hash_builder.rb', line 24 def primitive_typecast(value, type) case when type == Integer, type == Fixnum then value.to_i when type == Float then value.to_f when type == Symbol then value.to_sym when type == Array then array_typecast(value, ARRAY_TYPE_DEFAULT) when type == Hash then hash_typecast(value, HASH_TYPE_DEFAULT) else value end end |
.string_to_array(str) ⇒ Object
54 55 56 |
# File 'lib/hattr/hash_builder.rb', line 54 def string_to_array(str) str.tr('[]:" ', '').split(',') end |
.string_to_hash(str) ⇒ Object
50 51 52 |
# File 'lib/hattr/hash_builder.rb', line 50 def string_to_hash(str) Hash[str.tr('{}:" ', '').split(',').map { |pair| pair.split('=>') }] end |
.typecast(value, type) ⇒ Object
16 17 18 19 20 21 22 |
# File 'lib/hattr/hash_builder.rb', line 16 def typecast(value, type) case when type.class == Hash then hash_typecast(value, type) when type.class == Array then array_typecast(value, type) else primitive_typecast(value, type) end end |