Starter Step

New proxy_field plugin

Posted 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…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


  • Dave: I can tell you're a ruby guy because you forgot the 'return' keyword. Thanks for the tip though!
  • Chandrashekhar H M: Hi, Thanks its working fine in iOS 6 but not in iOS 7.0. Any Suggestion on this.
  • Coeur: To change a rootViewController, without all this TVNavigationController : myNewRoot = [[UIViewController alloc] init]; myNavigationController.view
%d bloggers like this: