This plugin provides a variety of utilities for numeric columns in an ActiveRecord model.
It allows you to accept commas, currency symbols, and percent symbols from users for integer and float columns.
(This is a fork of Doug Ramsay’s CommaParser, which I think is an elegant solution for commas, so I mod’d his code instead of writing it from scratch. http://github.com/dramsay/comma_parser/tree/master).
create_table :cities do |t|
t.string :name, :limit => 20, :null => false
t.integer :population, :default => 0, :null => true
t.float :annual_budget, :annual_expenses, :default => 0, :null => true
t.float :percent_unemployed, :default => 0, :null => true
t.integer :historic, :default => 0, :null => true
end
class City < ActiveRecord::Base
allow_commas :population
allow_currency_symbols :annual_budget, :annual_expenses
allow_percent_symbols :percent_unemployed
# rest of class
end
Now the user can type population “1,000,000” into a form and it will still save correctly as “1000000” instead of “1”. This saves you the hassle of stripping out commas either in JavaScript or in the controller.
You can also strip any arbitrary characters, like so:
class City < ActiveRecord::Base
allow_characters :annual_budget, annual_expenses, :characters => '.€|_'
end
or as an array-like object
class City < ActiveRecord::Base
allow_characters :annual_budget, annual_expenses, :characters => %w[. € | _]
end
For Rails 2.1 and above:
ruby script/plugin install git://github.com/twerth/sexy_numerics.git
To upgrade:
ruby script/plugin install git://github.com/twerth/sexy_numerics.git —force
My intention is to add other numeric Model based features.
Released under the MIT license