Browse files

Basic active record integration for converting numeric values

  • Loading branch information...
1 parent 0f52de8 commit acf1332cef62db76ae70f12ee57060b3f40750fb @carlosantoniodasilva committed Jan 16, 2011
Showing with 71 additions and 1 deletion.
  1. +5 −1 Gemfile
  2. +1 −0 i18n-alchemy.gemspec
  3. +3 −0 lib/i18n-alchemy.rb
  4. +27 −0 lib/i18n-alchemy/active_record.rb
  5. +24 −0 test/i18n-alchemy/active_record_test.rb
  6. +11 −0 test/test_helper.rb
View
6 Gemfile
@@ -1,4 +1,8 @@
source "http://rubygems.org"
-# Specify your gem's dependencies in i18n-alchemy.gemspec
gemspec
+
+group :test do
+ gem "sqlite3-ruby", "~> 1.3.2"
+ gem "ruby-debug19"
+end
View
1 i18n-alchemy.gemspec
@@ -19,5 +19,6 @@ Gem::Specification.new do |s|
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
+ s.add_dependency "activerecord", "~> 3.0.3"
s.add_dependency "i18n", "~> 0.5.0"
end
View
3 lib/i18n-alchemy.rb
@@ -1,2 +1,5 @@
require "i18n"
require "i18n-alchemy/numeric_parser"
+
+require "active_record"
+require "i18n-alchemy/active_record"
View
27 lib/i18n-alchemy/active_record.rb
@@ -0,0 +1,27 @@
+module I18n
+ module Alchemy
+ module ActiveRecord
+ def write_attribute(attribute_name, value)
+ value = parse_numeric_value(value) if numeric_column?(attribute_name)
+ super
+ end
+
+ private
+
+ def numeric_column?(attribute)
+ column = column_for_attribute(attribute.to_s)
+ [:decimal, :numeric, :float].include?(column.type)
+ end
+
+ def parse_numeric_value(value)
+ numeric_parser.parse(value)
+ end
+
+ def numeric_parser
+ @i18n_alchemy_numeric_parser ||= I18n::Alchemy::NumericParser.new
+ end
+ end
+ end
+end
+
+ActiveRecord::Base.send :include, I18n::Alchemy::ActiveRecord
View
24 test/i18n-alchemy/active_record_test.rb
@@ -0,0 +1,24 @@
+require "test_helper"
+
+class ActiveRecordTest < MiniTest::Unit::TestCase
+ def setup
+ @product = Product.new
+ end
+
+ def test_numeric_columns_accept_numeric_values
+ @product.price = 1.99
+ assert_equal 1.99, @product.price
+ end
+
+ def test_numeric_columns_accept_string_values
+ @product.price = "1.2"
+ assert_equal 1.2, @product.price
+ end
+
+ def test_numeric_columns_accept_localized_values
+ I18n.with_locale :pt do
+ @product.price = "1,2"
+ assert_equal 1.2, @product.price
+ end
+ end
+end
View
11 test/test_helper.rb
@@ -9,3 +9,14 @@
I18n.default_locale = :en
I18n.locale = :en
I18n.load_path << Dir[File.expand_path("../locale/*.yml", __FILE__)]
+
+ActiveRecord::Base.establish_connection(
+ :adapter => "sqlite3",
+ :database => ":memory:"
+)
+ActiveRecord::Base.connection.create_table :products do |t|
+ t.decimal :price
+end
+
+class Product < ActiveRecord::Base
+end

0 comments on commit acf1332

Please sign in to comment.