Skip to content

Commit

Permalink
Add rational typecaster
Browse files Browse the repository at this point in the history
fixes #3
  • Loading branch information
joker1007 committed Oct 21, 2014
1 parent d36f9c4 commit b5f2324
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/attr_typecastable/types.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
require 'attr_typecastable/types/date'
require 'attr_typecastable/types/date_time'
require 'attr_typecastable/types/float'
require 'attr_typecastable/types/rational'
require 'attr_typecastable/types/boolean'
require 'attr_typecastable/types/object'

Expand All @@ -25,6 +26,7 @@ module Types
::Date => AttrTypecastable::Types::Date,
::DateTime => AttrTypecastable::Types::DateTime,
::Float => AttrTypecastable::Types::Float,
::Rational => AttrTypecastable::Types::Rational,
::Boolean => AttrTypecastable::Types::Boolean,
}.freeze

Expand Down
18 changes: 18 additions & 0 deletions lib/attr_typecastable/types/rational.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
require 'attr_typecastable/types/exception'
require 'attr_typecastable/types/base'

module AttrTypecastable
module Types
class Rational < Base
def do_typecast(value)
return value if value.is_a?(::Rational)

if value.respond_to?(:to_r)
value.to_r
else
raise CastError, "value does not have `to_r` method"
end
end
end
end
end
4 changes: 4 additions & 0 deletions spec/attr_typecastable_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ class User
typed_attr_accessor :birthday_datetime, DateTime
typed_attr_accessor :age, Integer
typed_attr_accessor :bmi, Float
typed_attr_accessor :bmi_r, Rational
typed_attr_accessor :property, CastToMoney
typed_attr_accessor :adult, Boolean
typed_attr_accessor :admin, Boolean, true_value: ["yes"]
Expand Down Expand Up @@ -105,6 +106,9 @@ def initialize(name: nil, default_name: nil)
user.bmi = "20.1"
assert { user.bmi > 20.09 && user.bmi < 20.11 }

user.bmi = "20.1"
assert { user.bmi == "20.1".to_r }

user.property = 10000
assert { user.property == Money.new(10000) }

Expand Down

0 comments on commit b5f2324

Please sign in to comment.