Skip to content

Instantly share code, notes, and snippets.

@pepe
Forked from cdcarter/form_helper.rb
Created June 12, 2011 17:12
Show Gist options
  • Save pepe/1021773 to your computer and use it in GitHub Desktop.
Save pepe/1021773 to your computer and use it in GitHub Desktop.
NS Form Helper Class
class FormHelper
attr_accessor :form
def initialize(nsform=nil)
@form = nsform
end
def length
form.numberOfRows
end
def to_hash
(0...self.length).inject({}) {|m,o|
o = self.form.cellAtIndex(o)
m[o.title] = o.stringValue
m
}
end
def to_a
(0...self.length).map {|x| self.form.cellAtIndex(x) }
end
def sum
(0...self.length).inject(0) {|m,o|
o = self.form.cellAtIndex(o)
m + o.intValue
}
end
def values
self.to_hash.values
end
def [](key)
if key.is_a?(String)
self.to_hash[key]
elsif key.is_a?(Integer)
self.to_a[key]
end
end
end

With MacRuby, you can easily extend or wrap any Cocoa class. The class below, FormHelper, gives a more ruby like interface to the NSForm, a fairly useful control in AppKit. All of a sudden

form.cellAtIndex(1).objectValue

becomes

form_helper["Email Address"]

So much boilerplate and standard code you'd write in Cocoa can be abstracted to neat helper classes with ruby's classy meta-programming.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment