Permalink
Browse files

Make lambda usable in options database/model unit.

  • Loading branch information...
Ronni Rasmussen Ronni Rasmussen
Ronni Rasmussen authored and Ronni Rasmussen committed Mar 13, 2012
1 parent 50ff6af commit 0c9bef02c7031fda38b74afed7676bc243ede51e
Showing with 12 additions and 5 deletions.
  1. +10 −3 lib/measurement.rb
  2. +2 −2 measurement.gemspec
View
@@ -3,22 +3,29 @@ def self.included(base)
base.extend ClassMethods
end
+ def measurement_convert(name, from, to)
+ from = from.call if from.is_a?(Proc)
+ to = to.call if to.is_a?(Proc)
+
+ self[name] = self[name].from(from).to(to).to_f.round(3) if !self[name].nil? && from != to
+ end
+
module ClassMethods
def measurement(*args, &block)
options = { :model_unit => :meter, :database_unit => :meter }
options.merge!(args.pop) if args.last.kind_of? Hash
args.each do |name|
before_save do |record|
- self[name] = self[name].from(options[:model_unit]).to(options[:database_unit]).to_f.round(3) if !self[name].nil? && options[:model_unit] != options[:database_unit]
+ measurement_convert(name, options[:model_unit], options[:database_unit])
end
after_save do |record|
- self[name] = self[name].from(options[:database_unit]).to(options[:model_unit]).to_f.round(3) if !self[name].nil? && options[:model_unit] != options[:database_unit]
+ measurement_convert(name, options[:database_unit], options[:model_unit])
end
after_initialize do |record|
- self[name] = self[name].from(options[:database_unit]).to(options[:model_unit]).to_f.round(3) if !self[name].nil? && options[:model_unit] != options[:database_unit]
+ measurement_convert(name, options[:database_unit], options[:model_unit])
end
end
end
View
@@ -6,11 +6,11 @@ Gem::Specification.new do |s|
s.required_rubygems_version = Gem::Requirement.new(">= 1.2") if s.respond_to? :required_rubygems_version=
s.authors = ["Ronni Steen Rasmussen"]
- s.date = "2012-03-12"
+ s.date = "2012-03-13"
s.description = "Automaticly convert measurements units."
s.email = "ronni.rasmussen@gmail.com"
s.extra_rdoc_files = ["README.md", "lib/measurement.rb"]
- s.files = ["README.md", "Rakefile", "lib/measurement.rb", "measurement.gemspec", "Manifest"]
+ s.files = ["README.md", "Rakefile", "lib/measurement.rb", "Manifest", "measurement.gemspec"]
s.homepage = "http://github.com/Iumentum/measurement"
s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Measurement", "--main", "README.md"]
s.require_paths = ["lib"]

0 comments on commit 0c9bef0

Please sign in to comment.