Last active
December 18, 2015 00:38
-
-
Save delba/5697614 to your computer and use it in GitHub Desktop.
Store formatted duration like 03:30 in seconds
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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