Skip to content

Commit

Permalink
Initial release
Browse files Browse the repository at this point in the history
  • Loading branch information
fnando committed Nov 6, 2010
0 parents commit 9db64d3
Show file tree
Hide file tree
Showing 12 changed files with 307 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pkg/*
*.gem
.bundle
4 changes: 4 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
source "http://rubygems.org"

# Specify your gem's dependencies in formatted_attributes.gemspec
gemspec
79 changes: 79 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
PATH
remote: .
specs:
formatted_attributes (0.1.0)
activerecord

GEM
remote: http://rubygems.org/
specs:
abstract (1.0.0)
actionpack (3.0.1)
activemodel (= 3.0.1)
activesupport (= 3.0.1)
builder (~> 2.1.2)
erubis (~> 2.6.6)
i18n (~> 0.4.1)
rack (~> 1.2.1)
rack-mount (~> 0.6.12)
rack-test (~> 0.5.4)
tzinfo (~> 0.3.23)
activemodel (3.0.1)
activesupport (= 3.0.1)
builder (~> 2.1.2)
i18n (~> 0.4.1)
activerecord (3.0.1)
activemodel (= 3.0.1)
activesupport (= 3.0.1)
arel (~> 1.0.0)
tzinfo (~> 0.3.23)
activesupport (3.0.1)
archive-tar-minitar (0.5.2)
arel (1.0.1)
activesupport (~> 3.0.0)
builder (2.1.2)
columnize (0.3.1)
diff-lcs (1.1.2)
erubis (2.6.6)
abstract (>= 1.0.0)
i18n (0.4.1)
linecache19 (0.5.11)
ruby_core_source (>= 0.1.4)
rack (1.2.1)
rack-mount (0.6.13)
rack (>= 1.0.0)
rack-test (0.5.6)
rack (>= 1.0)
rspec (2.0.1)
rspec-core (~> 2.0.1)
rspec-expectations (~> 2.0.1)
rspec-mocks (~> 2.0.1)
rspec-core (2.0.1)
rspec-expectations (2.0.1)
diff-lcs (>= 1.1.2)
rspec-mocks (2.0.1)
rspec-core (~> 2.0.1)
rspec-expectations (~> 2.0.1)
ruby-debug-base19 (0.11.24)
columnize (>= 0.3.1)
linecache19 (>= 0.5.11)
ruby_core_source (>= 0.1.4)
ruby-debug19 (0.11.6)
columnize (>= 0.3.1)
linecache19 (>= 0.5.11)
ruby-debug-base19 (>= 0.11.19)
ruby_core_source (0.1.4)
archive-tar-minitar (>= 0.5.2)
sqlite3-ruby (1.3.1)
tzinfo (0.3.23)

PLATFORMS
ruby

DEPENDENCIES
actionpack
activerecord
formatted_attributes!
rspec (>= 2.0.0)
ruby-debug19
sqlite3-ruby
65 changes: 65 additions & 0 deletions README.rdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
= Formatted Attributes

Sometimes you want to use a proxy attribute that will be formatted while displaying its value or receiving data from user.

== Install

gem install formatted_attributes

== Usage

A formatted attribute will require two methods: <tt>format_to_#{formatter}</tt> and <tt>format_from_#{formatter}</tt>. The <tt>format_to_*</tt> method will convert the formatted value to the original value and the <tt>format_from_*</tt> method will do the other way around, converting the original value to the formatted version.

See an example on how to format prices from strings like <tt>1,23</tt> to cents like <tt>123</tt> and vice-versa.

class Product < ActiveRecord::Base
include ActionView::Helpers::NumberHelper

formatted :price, :with => :cents

private
def format_to_cents(amount)
_, operator, number, precision = *number.to_s.match(/^([+-])?(\d+)(?:[,.](\d+))?$/)
(BigDecimal("#{operator}#{number}.#{precision.to_i}") * 100).to_i
end

def format_from_cents(amount)
number = BigDecimal(number.to_s) / 100
number_to_currency(number, :unit => "", :separator => ",", :delimiter => "")
end
end

product = Product.new(:formatted_price => "1,23")
product.price
#=> 123

product.price = 456
product.formatted_price
#=> "4,56"

== Maintainer

* Nando Vieira (http://nandovieira.com.br)

== License

(The MIT License)

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
5 changes: 5 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
require "bundler"
Bundler::GemHelper.install_tasks

require "rspec/core/rake_task"
RSpec::Core::RakeTask.new
25 changes: 25 additions & 0 deletions formatted_attributes.gemspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "formatted_attributes/version"

Gem::Specification.new do |s|
s.name = "formatted_attributes"
s.version = FormattedAttributes::Version::STRING
s.platform = Gem::Platform::RUBY
s.authors = ["Nando Vieira"]
s.email = ["fnando.vieira@gmail.com"]
s.homepage = "http://rubygems.org/gems/formatted_attributes"
s.summary = "Add formatted methods for ActiveRecord attributes"
s.description = "Sometimes you need to expose a helper method that will convert its value before saving it to the database. This gem will add `formatted_` suffix to the attributes you specify."

s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]

s.add_dependency "activerecord"
s.add_development_dependency "rspec", ">= 2.0.0"
s.add_development_dependency "sqlite3-ruby"
s.add_development_dependency "actionpack"
s.add_development_dependency "ruby-debug19"
end
5 changes: 5 additions & 0 deletions lib/formatted_attributes.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
require "active_record"
require "formatted_attributes/active_record"
require "formatted_attributes/version"

ActiveRecord::Base.send :include, FormattedAttributes::ActiveRecord
39 changes: 39 additions & 0 deletions lib/formatted_attributes/active_record.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
module FormattedAttributes
module ActiveRecord
def self.included(base)
base.instance_eval do
include InstanceMethods
extend ClassMethods
end
end

module ClassMethods
def formatted(*args)
options = args.extract_options!

args.each do |attr|
accessible_attributes << "formatted_#{attr}"

class_eval <<-RUBY
def #{attr}=(value)
@formatted_#{attr} = nil
write_attribute :#{attr}, value
end
def formatted_#{attr}
@formatted_#{attr} ||= format_from_#{options[:with]}(send(:#{attr}))
end
def formatted_#{attr}=(value)
self.send :#{attr}=, format_to_#{options[:with]}(value)
@formatted_#{attr} = value
end
RUBY
end
end
end

module InstanceMethods
end
end
end
8 changes: 8 additions & 0 deletions lib/formatted_attributes/version.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module FormattedAttributes
module Version
MAJOR = 0
MINOR = 1
PATCH = 0
STRING = "#{MAJOR}.#{MINOR}.#{PATCH}"
end
end
44 changes: 44 additions & 0 deletions spec/formatted_attributes_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
require "spec_helper"

describe FormattedAttributes do
subject { Product.new }

context "formatted methods" do
it "should add getters" do
subject.should respond_to(:formatted_price)
subject.should respond_to(:formatted_shipping)
end

it "should add setters" do
subject.should respond_to(:formatted_price=)
subject.should respond_to(:formatted_shipping=)
end

it "should set initial value" do
subject.price = 12300
subject.formatted_price.should == "123,00"
end

it "should update formatted price" do
subject.price = 12300
subject.formatted_price.should == "123,00"

subject.price = 45600
subject.formatted_price.should == "456,00"
end

it "should set formatted value" do
subject.price = 12300
subject.formatted_price = "456,78"
subject.formatted_price.should == "456,78"
subject.price.should == 45678

subject.shipping = 67800
subject.formatted_shipping = "345,67"
subject.formatted_shipping.should == "345,67"
subject.shipping.should == 34567

subject.should be_valid
end
end
end
5 changes: 5 additions & 0 deletions spec/schema.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
ActiveRecord::Schema.define(:version => 0) do
create_table :products do |t|
t.integer :price, :shipping, :default => 0, :null => false
end
end
25 changes: 25 additions & 0 deletions spec/spec_helper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
require "formatted_attributes"
require "active_support/all"
require "action_view/helpers/number_helper"

ActiveRecord::Base.establish_connection :adapter => "sqlite3", :database => ":memory:"

load File.dirname(__FILE__) + "/schema.rb"

class Product < ActiveRecord::Base
include ActionView::Helpers::NumberHelper
formatted :price, :shipping, :with => :cents

validates_numericality_of :price, :shipping, :only_integer => true

private
def format_to_cents(number)
_, operator, number, precision = *number.to_s.match(/^([+-])?(\d+)(?:[,.](\d+))?$/)
(BigDecimal("#{operator}#{number}.#{precision.to_i}") * 100).to_i
end

def format_from_cents(number)
number = BigDecimal(number.to_s) / 100
number_to_currency(number, :unit => "", :separator => ",", :delimiter => "")
end
end

0 comments on commit 9db64d3

Please sign in to comment.