Skip to content

Instantly share code, notes, and snippets.

@delba
Last active December 18, 2015 00:38
Show Gist options
  • Select an option

  • Save delba/5697614 to your computer and use it in GitHub Desktop.

Select an option

Save delba/5697614 to your computer and use it in GitHub Desktop.
Store formatted duration like 03:30 in seconds
class Song < ActiveRecord::Base
def length=(length)
return unless length =~ /\A\d+:\d{2}\z/
minutes, seconds = length.split(':').map(&:to_i)
write_attribute(:length, minutes * 60 + seconds)
end
def length
return unless length = read_attribute(:length)
"%02d:%02d" % length.divmod(60)
end
end
require 'test_helper'
class SongTest < ActiveSupport::TestCase
setup do
@song = Song.new(length: '01:30')
end
test "length=(length)" do
assert_equal 90, @song.read_attribute(:length)
end
test "length" do
assert_equal '01:30', @song.length
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment