Class: Munson::Attribute

Inherits:
Object show all
Defined in:
lib/munson/attribute.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, cast_type, options = {}) ⇒ Attribute

Returns a new instance of Attribute.



7
8
9
10
11
12
13
# File 'lib/munson/attribute.rb', line 7

def initialize(name, cast_type, options={})
  options[:default] ||= nil
  options[:array]   ||= false
  @name      = name
  @cast_type = cast_type
  @options   = options
end

Instance Attribute Details

#cast_typeObject (readonly)

Returns the value of attribute cast_type.



4
5
6
# File 'lib/munson/attribute.rb', line 4

def cast_type
  @cast_type
end

#nameObject (readonly)

Returns the value of attribute name.



3
4
5
# File 'lib/munson/attribute.rb', line 3

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



5
6
7
# File 'lib/munson/attribute.rb', line 5

def options
  @options
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 (@options[: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_valueObject



65
66
67
68
69
70
71
72
73
74
# File 'lib/munson/attribute.rb', line 65

def default_value
  case @options[:default]
  when Proc
    @options[:default].call
  when nil
    @options[:array] ? [] : nil
  else
    @options[: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 options[:serialize]
  when Proc
    options[:serialize].call(value)
  when Symbol
    value.send(options[:serialize])
  else
    value
  end
end