Posted by: Jake Dempsey on: October 31, 2009
I spent some time this week and wrote some small plugins. I’ll do a small write for each to explain the purpose and usage. The first plugin is the proxy_field plugin. For Bidbuddy (personal project) I only have about 10 models, but for each model there are a ton of fields that each represent a time duration. For example a field may represent how long a specific aircraft is used for a given schedule. The time is a duration so I have to store the value in seconds in the database. What I found was that I had helpers that would convert those column values in to hours, minutes, days, etc. While this works, it doesn’t feel right. I would rather just get the value of the column and call to_hours on it. I could open the Integer class and add my to_hours method to it, but I would like something a bit more generic that could be reused for other situations. What I came up with was this syntax:
class Block < ActiveRecord::Base
proxy_field [:tduty, :tblk], :as => DurationField
end
class DurationField
def initialize(seconds)
@seconds = seconds
end
def to_hours
@seconds / 60 / 60
end
#Other useful methods would go here
#to_seconds, to_minutes, to_days, to_weeks, etc...
end
This allows me to proxy any ActiveRecord field into another object. It basically allows you to deserialize any column data.
Old Way:
def seconds_to_hours(seconds)
seconds / 60 / 60
end
b = Block.find(CONDITIONS_HERE)
puts seconds_to_hours(b.tduty)
New Way:
b = Block.find(CONDITIONS_HERE) puts b.tduty.to_hours
Install:
./script/plugin install git://github.com/angelo0000/proxy_field.git
I have not decided yet how to handle nil columns. Its not a technical challenge but more of a design decision. The plugin could return nil when you called the method to get the proxy: b.tduty would return nil. Or that could be up to the proxy object class to return nil for each method if the inializer got a nil. In my duration example to_hours method would nil if @seconds was nil. I’m not sure what I would prefer. I would love a suggestion…