From 1896689614ef64a21e1e6e060ddbbbf2f8165699 Mon Sep 17 00:00:00 2001 From: Andy Meneely Date: Sun, 1 Feb 2015 23:48:09 -0500 Subject: [PATCH] Refactoring out the unit conversion to its own place --- lib/squib/args/unit_conversion.rb | 21 +++++++++++++++++++++ lib/squib/input_helpers.rb | 8 ++------ spec/args/unit_conversion_spec.rb | 22 ++++++++++++++++++++++ 3 files changed, 45 insertions(+), 6 deletions(-) create mode 100644 lib/squib/args/unit_conversion.rb create mode 100644 spec/args/unit_conversion_spec.rb diff --git a/lib/squib/args/unit_conversion.rb b/lib/squib/args/unit_conversion.rb new file mode 100644 index 0000000..4ef3eb0 --- /dev/null +++ b/lib/squib/args/unit_conversion.rb @@ -0,0 +1,21 @@ +require 'squib/constants' + +module Squib + module Args + module UnitConversion + + module_function + def parse(arg, dpi=300) + case arg.to_s.rstrip + when /in$/ #ends with "in" + arg.rstrip[0..-2].to_f * dpi + when /cm$/ #ends with "cm" + arg.rstrip[0..-2].to_f * dpi * INCHES_IN_CM + else + arg + end + end + + end + end +end \ No newline at end of file diff --git a/lib/squib/input_helpers.rb b/lib/squib/input_helpers.rb index a971232..2e6d4bd 100644 --- a/lib/squib/input_helpers.rb +++ b/lib/squib/input_helpers.rb @@ -1,4 +1,5 @@ require 'squib/constants' +require 'squib/args/unit_conversion' module Squib # :nodoc: @@ -200,12 +201,7 @@ module Squib Squib::UNIT_CONVERSION_PARAMS.each_pair do |param_name, api_param| if needed_params.include? param_name opts[api_param].each_with_index do |arg, i| - case arg.to_s.rstrip - when /in$/ #ends with "in" - opts[api_param][i] = arg.rstrip[0..-2].to_f * @dpi - when /cm$/ #ends with "cm" - opts[api_param][i] = arg.rstrip[0..-2].to_f * @dpi * Squib::INCHES_IN_CM - end + opts[api_param][i] = Args::UnitConversion.parse(arg, @dpi) end end end diff --git a/spec/args/unit_conversion_spec.rb b/spec/args/unit_conversion_spec.rb new file mode 100644 index 0000000..37e1d38 --- /dev/null +++ b/spec/args/unit_conversion_spec.rb @@ -0,0 +1,22 @@ +require 'spec_helper' +require 'squib/args/unit_conversion' + +describe Squib::Args::UnitConversion do + + it 'does nothing on just numbers' do + expect(subject.parse(20)).to eq(20) + end + + it 'strips trailing whitespace' do + expect(subject.parse('1in ')).to eq(300) + end + + it 'is ok w/internal whitesapce' do + expect(subject.parse('1 in')).to eq(300) + end + + it 'does cm' do + expect(subject.parse('1cm')).to eq(118.1102361) + end + +end \ No newline at end of file