Class: Munson::Attribute
- Inherits:
-
Object
- Object
- Munson::Attribute
- Defined in:
- lib/munson/attribute.rb
Instance Attribute Summary collapse
-
#cast_type ⇒ Object
readonly
Returns the value of attribute cast_type.
-
#name ⇒ Object
readonly
Returns the value of attribute name.
-
#options ⇒ Object
readonly
Returns the value of attribute options.
Instance Method Summary collapse
-
#cast(value) ⇒ Object
Super naive casting!.
- #cast_value(value) ⇒ Object
- #default_value ⇒ Object
-
#initialize(name, cast_type, options = {}) ⇒ Attribute
constructor
A new instance of Attribute.
-
#process(value) ⇒ Object
Process a raw JSON value.
-
#serialize(value) ⇒ Object
Serializes the value back to JSON datatype.
Constructor Details
#initialize(name, cast_type, options = {}) ⇒ Attribute
7 8 9 10 11 12 13 |
# File 'lib/munson/attribute.rb', line 7 def initialize(name, cast_type, ={}) [:default] ||= nil [:array] ||= false @name = name @cast_type = cast_type = end |
Instance Attribute Details
#cast_type ⇒ Object (readonly)
Returns the value of attribute cast_type.
4 5 6 |
# File 'lib/munson/attribute.rb', line 4 def cast_type @cast_type end |
#name ⇒ Object (readonly)
Returns the value of attribute name.
3 4 5 |
# File 'lib/munson/attribute.rb', line 3 def name @name end |
#options ⇒ Object (readonly)
Returns the value of attribute options.
5 6 7 |
# File 'lib/munson/attribute.rb', line 5 def end |
Instance Method Details
#cast(value) ⇒ Object
Super naive casting!
21 22 23 24 25 26 |
# File 'lib/munson/attribute.rb', line 21 def cast(value) return ([:array] ? [] : nil) if value.nil? value.is_a?(Array) ? value.map { |v| cast_value(v) } : cast_value(value) end |
#cast_value(value) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/munson/attribute.rb', line 28 def cast_value(value) return nil if value.nil? case cast_type when Proc cast_type.call(value) when :string, :to_s, String value.to_s when :integer, :to_i, Fixnum value.to_i when :bigdecimal BigDecimal.new(value.to_s) when :float, :to_f, Float value.to_f when :date, Date Date.parse(value) rescue nil when :time, Time Time.parse(value) rescue nil else value end end |
#default_value ⇒ Object
65 66 67 68 69 70 71 72 73 74 |
# File 'lib/munson/attribute.rb', line 65 def default_value case [:default] when Proc [:default].call when nil [:array] ? [] : nil else [:default].clone end end |
#process(value) ⇒ Object
Process a raw JSON value
16 17 18 |
# File 'lib/munson/attribute.rb', line 16 def process(value) value.nil? ? default_value : cast(value) end |
#serialize(value) ⇒ Object
Serializes the value back to JSON datatype
54 55 56 57 58 59 60 61 62 63 |
# File 'lib/munson/attribute.rb', line 54 def serialize(value) case [:serialize] when Proc [:serialize].call(value) when Symbol value.send([:serialize]) else value end end |