From: Tim B. <tim...@gm...> - 2006-09-01 15:07:54
|
On Sep 1, 2006, at 1:28 AM, Eloy Duran wrote: > I'm very interested to hear about it too.... > > I think you should take a look at: > http://wiki.rubyonrails.com/rails/pages/HowToUseActiveRecordOutsideRails > > On 9/1/06, Jonathan Paisley <jp...@dc...> wrote: >> On Thu, 24 Aug 2006 5:54pm +0200, Cornelius Jaeger wrote: >> >>> Has anyone played with using rails as a backend to rubycocoa. >>> i know there is coredata, which i love, but it would allow cross >>> platform development of business objects and db access / >>> abstraction. >>> Has anyone got an example? >> >> Are you talking about using ActiveRecord (a component of rails) as >> a data >> storage mechanism for a RubyCocoa application? >> >> I've not tried it. But I'd be interested to hear of how it works out. I've done this. Here are some code excerpts from a program that displays ActiveRecord objects in NSTableViews. The key element is the ArrayTableModel class; it implements the data source protocol for the table view. class ArrayTableModel < OSX::NSObject attr_accessor :array def initWithArray(array) @array = array self end def numberOfRowsInTableView(view) @array.length end def tableView_objectValueForTableColumn_row(view,column,row) @array[row].send(column.identifier.to_s).to_s end def tableView_shouldEditTableColumn_row(view,column,row) false end end Once you've created an instance of your model, you can programmatically create and configure a table view like this: def tv(columns, model) view = TableView.alloc.initWithFrame([0,0,500,200]) view.setAutoresizingMask(OSX::NSViewWidthSizable + OSX::NSViewHeightSizable) view.setColumns columns view.setDelegate model view.setDataSource model view end Here's the top-level code, which uses the Quote class (a subclass of ActiveRecord) to look up price quotes from a MySQL database. The column names/identifiers are simply fields in the database which the data source sends to ActiveRecord objects as messages. def tableview(symbol = "AAPL", daterange=nil) quotes = Quote.find_all_by_symbol(symbol).sort_by{|ed| -ed.date.to_i} tv(['date', 'open', 'last', 'high', 'low', 'volume'], ArrayTableModel.alloc.initWithArray(quotes)) end You'll have to put this somewhere in your code to connect to the database: ActiveRecord::Base.establish_connection( :adapter => "mysql", :host => "localhost", :username => "my-username", :password => "my-password", :database => "my-database" ) It's easy, but watch out for name conflicts. ActiveRecord defines a lot of messages. Some of them have names that might conflict with message names on the Objective-C side of your project, meaning that you'll have to use the "oc_" prefix to call those Objective-C methods from Ruby. Tim |