Permalink
Browse files

added meaningful persisting to numeric and subclasses

  • Loading branch information...
1 parent 68ddbde commit 9714e17510c6fd2136614cc5319b5ad077f68804 @hannesg committed Oct 19, 2011
Showing with 80 additions and 0 deletions.
  1. +50 −0 lib/splash/core_ext/numeric.rb
  2. +30 −0 spec/lib/numeric_spec.rb
@@ -0,0 +1,50 @@
+# -*- encoding : utf-8 -*-
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the Affero GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+#
+# (c) 2010 by Hannes Georg
+#
+class Numeric
+
+ def self.to_saveable(x)
+
+ begin
+ if self.respond_to? :coerce
+ x = self.coerce(x)
+ end
+ rescue ArgumentError
+ end
+
+ return x if x.kind_of?(Fixnum) or x.kind_of?(Float)
+
+ begin
+ return Float(x)
+ rescue ArgumentError
+ return Integer(x) rescue 0
+ end
+
+ end
+
+ def self.from_saveable(x)
+
+ begin
+ if self.respond_to? :coerce
+ return self.coerce(x)
+ end
+ rescue ArgumentError
+ end
+
+ return Float(x)
+ end
+
+end
View
@@ -0,0 +1,30 @@
+# -*- encoding : utf-8 -*-
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the Affero GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+#
+# (c) 2010 by Hannes Georg
+#
+require 'bigdecimal'
+
+describe Numeric do
+
+
+ it "should be saved as fixnum or float" do
+
+ Float.to_saveable(Float("2.3")).should be_kind_of(Float)
+ BigDecimal.to_saveable(BigDecimal("2.3")).should be_kind_of(Float)
+ Fixnum.to_saveable(Integer("2")).should be_kind_of(Fixnum)
+
+ end
+
+end

0 comments on commit 9714e17

Please sign in to comment.