Jun 032009

In a few places I need to store the length of a video. To keep things simple and fast, I’m using an :integer, and storing the length in seconds of the video file. This is all well and good when it comes to indexing and sorting in the database, when it comes to user interaction its really junky. No one wants to know that a video 421 seconds long is 7 minutes, and 1 second long… and I didn’t want people to have to convert 3 hours, 45 minutes, and 10 seconds into a huge integer.

At first I implemented it up quick and dirty in the edit code of controller for the portion of code that needed this conversion, however as I started to build out a few other items I realized I was going to be needing the same feature so I moved it to a plugin.

You should note, this is my first time authoring a plugin and my first time trying to make it into a gem. It works for me, so I would hope it can work for you too. Its pretty straight-forward to setup and use. Here’s my model:

class Video < ActiveRecord::Base

acts_as_timecode :column => :duration


Now I can use this cool new timecode field in my views and controllers. For example, in my edit.html.erb I use <%= f.text_field :timecode %>. which generates a textbox with the video duration in it, looking like 00:34:12 or however long the video is. Hitting the save button works as expected, updating the duration field in my database to the correct seconds value (2052 in this case). Because I don’t always like to type leading zeros, the timecode field can take the following formats: HH:MM:SS:FF, HH:MM:SS, MM:SS, SS. The frame implementation isn’t very useful, but it will round your frames to the nearest second value, based on the :fps configuration setting (defaulted at 30).

At some point I might expand it, but it will depend on what I need it to do.

You can check it out on GitHub: http://github.com/bamnet/acts-as-timecode/