Module: FieldHelpers::ClassMethods

Defined in:
lib/volt/models/field_helpers.rb

Instance Method Summary collapse

Instance Method Details

#field(name, klass = nil) ⇒ Object

field lets you declare your fields instead of using the underscore syntax. An optional class restriction can be passed in.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/volt/models/field_helpers.rb', line 8

def field(name, klass = nil)
  if klass && ![String, Numeric].include?(klass)
    fail FieldHelpers::InvalidFieldClass, 'valid field types is currently limited to String or Numeric'
  end

  if klass
  # Add type validation, execpt for String, since anything can be a string.
    unless klass == String
      validate name, type: klass
    end
  end

  define_method(name) do
    get(name)
  end

  define_method(:"#{name}=") do |val|
    # Check if the value assigned matches the class restriction
    if klass
      # Cast to the right type
      if klass == String
        val = val.to_s
      elsif klass == Numeric
        begin
          orig = val
          unless val.is_a?(Numeric)
            val = Float(val)
          end

          if RUBY_PLATFORM == 'opal'
            # Opal has a bug in 0.7.2 that gives us back NaN without an
            # error sometimes.
            val = orig if val.nan?
          end
        rescue TypeError, ArgumentError => e
          # ignore, unmatched types will be caught below.
        end
      end
    end

    set(name, val)
  end
end