Method: CatForms::Form::ClassMethods#attribute

Defined in:
lib/cat_forms.rb

#attribute(name, type, opts = {}) ⇒ Object

Overrides how Virtus handles attributes of the wrong type. Ideally virtus would coerce everything to the right type, use the default, or return nil. There’s a related discussion here: github.com/solnic/virtus/issues/99



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/cat_forms.rb', line 43

def attribute(name, type, opts = {})
  super(name, type, opts)
  define_method(name) do
    data = super()
    default_value = -> { opts[:default].respond_to?(:call) ? opts[:default].call : opts[:default] }

    # If they want a BigDecimal or Int, but data is a string, strip
    # the stuff of bad data and try to convert manually.
    if type == BigDecimal or type == Integer
      if data.class == String
        data.gsub!(/[^\d\.]/, '')
        if data.present?
          if type == BigDecimal
            data = BigDecimal.new(data)
          else
            data = Integer(data)
          end
        end
      end
    end

    #if type.class != Array and !data.is_a?(type) and !data.nil? and (type != CatForms::Boolean and !data.is_a?(Boolean))
      #puts "cat forms expected a #{type} for #{ name }, received #{ data.inspect }"
      #puts caller
    #end

    if type == CatForms::Boolean and (data == true or data == false)
      return data
    end

    if type.class == Array
      # Not validating more right now.
      return data
    end

    if data.is_a?(type)
      # Override for default string
      if type == String and opts.has_key?(:default) and data == ""
        return default_value.call
      else
        return data
      end
    end

    return default_value.call
  end
end