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
# 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

  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
        val = val.to_f
      end
    end

    set(name, val)
  end
end