lib/volt/models/field_helpers.rb in volt-0.9.3 vs lib/volt/models/field_helpers.rb in volt-0.9.4.pre1
- old
+ new
@@ -8,10 +8,15 @@
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
+ validate name, type: klass
+ end
+
define_method(name) do
get(name)
end
define_method(:"#{name}=") do |val|
@@ -19,10 +24,23 @@
if klass
# Cast to the right type
if klass == String
val = val.to_s
elsif klass == Numeric
- val = val.to_f
+ 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