Skip to content

Instantly share code, notes, and snippets.

@ayrton
Created November 10, 2012 12:18
Show Gist options
  • Save ayrton/4050908 to your computer and use it in GitHub Desktop.
Save ayrton/4050908 to your computer and use it in GitHub Desktop.
class Duration
attr_accessor :duration
def initialize(string)
@duration = string
end
def to_i
value_units.map(&:to_i).reduce(&:+)
end
private
def value_units
duration.gsub(' ', '').scan(/(\d+)([a-zA-Z]+)/).map { |value, unit|
ValueUnit.new(value, unit)
}
end
end
class ValueUnit
attr_accessor :value, :unit
def initialize(value, unit)
@value = value
@unit = unit
end
def to_i
value.to_i * unit_value
end
private
def unit_value
case unit
when /^h/ then 3600
when /^m/ then 60
when /^s/ then 1
else 0
end
end
end
require 'duration'
require 'spec_helper'
describe Duration do
context 'seconds' do
it { Duration.new('1s').to_i.should == 1 }
it { Duration.new('1sec').to_i.should == 1 }
it { Duration.new('1 sec').to_i.should == 1 }
end
context 'minutes' do
it { Duration.new('1m').to_i.should == 60 }
it { Duration.new('1min').to_i.should == 60 }
it { Duration.new('1 min').to_i.should == 60 }
end
context 'hours' do
it { Duration.new('1h').to_i.should == 3600 }
it { Duration.new('1hour').to_i.should == 3600 }
it { Duration.new('1 hour').to_i.should == 3600 }
end
context 'mix' do
it { Duration.new('1h 6 min 40 sec').to_i.should == 4000 }
end
context 'unknown unit' do
it { Duration.new('1 day 1 second').to_i.should == 1 }
end
end
def some_method(duration)
parsed_duration = 0
if duration.include? 'h'
parsed_duration += duration.match(/(\d+)h/).captures.first.to_i.send(:hour).to_i
duration = duration.match(/\d+h(.+)/).captures.first.strip
end
parsed_duration += duration.to_i.send(duration.split[1].gsub('min', 'minute').gsub('sec', 'second')).to_i
parsed_duration
end
@ayrton
Copy link
Author

ayrton commented Nov 10, 2012

Refactors old_broken_code.rb to a class Duration. Added spec, to have an idea what Duration should do; note that not all specs were green with old_broken_code.rb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment