Extending ActiveRecord for csv export... a better way?

As a new Ruby user (JRuby, actually), I’ve picked up this language with
a very specific purpose: to export data from a JDBC database into flat
files. I’ve figured out how to get the data out of the DB and into a
file, but it requires a bit too much configuration. My first stab
implementation requires me to define an activerecord class for each
table I want to export, and to define a method all_columns in each class
that lays out the columns in the correct order. I’ve also setup a
module (CSVable) that extends ActiveRecord so I can call the export
function directly on each class. Here is the code:

Module definition

module CSVable
extend ActiveRecord
class Base < ActiveRecord::Base
def self.export_table_to_csv(delimiter = “,”, options = nil)
File.open("#{self.table_name}.dat",
File::WRONLY|File::TRUNC|File::CREAT) do |file|
self.find(:all, options).each do |trow|
file.puts trow.all_columns.join(delimiter)
end
end
end
end
end

Class definitions

class USR_USER_ACCOUNT < CSVable::Base
set_table_name “USR.USER_ACCOUNT”
def all_columns
[ self.UID, self.USER_NAME, self.USER_INIT, self.ACTIVE_FLAG,
self.LAST_MODFD_TS ]
end
end

class GRP_GRP < CSVable::Base
set_table_name “GRP.GRP”
def all_columns
[ self.PARTY_ROLE_ASSIGN_PID, self.GRP_NBR_ID,
self.LAST_MODIFIED_TIMESTAMP ]
end
end

Usage for the module

USR_USER_ACCOUNT.export_table_to_csv("|")

The major problem with this approach is that I have to setup all the
column info for each of the 36 tables. Is there an easier way to get an
array of the columns while still retaining the original order?

I’ve tried using the attributes method, but since it returns a hash, the
columns are not in order. My dabbles with the columns method have not
been successful either. Any ideas?

I also have a feeling there is a much better way to implement the export
function…

Any help or suggestions are most appreciated!

-Adam

Hi Adam

In ActiveScaffold, there is a very nice export plugin called
activescaffoldxport.
Check it out, it may help you …

CCH

On Oct 31, 10:06 pm, Adam B. [email protected]

CCH wrote:

Hi Adam

In ActiveScaffold, there is a very nice export plugin called
activescaffoldxport.
Check it out, it may help you …

CCH
http://cch4rails.blogspot.com

On Oct 31, 10:06 pm, Adam B. <[email protected]

Thanks for the tip, I’ll take a look. Is this a Ruby plugin or RoR?

Pablo C. wrote:

Try http://rubyreports.org

On Oct 31, 8:06 am, Adam B. [email protected]

If anyone else is looking for the solution to Ruby and JDBC exports, see
the solution at Extending ActiveRecord for csv export... a better way? - Ruby - Ruby-Forum.

Hi Adam

On Oct 31, 10:06 pm, Adam B. <[email protected]

Thanks for the tip, I’ll take a look. Is this a Ruby plugin or RoR?

cch: It is a RoR plugin.

CCH

Try http://rubyreports.org

On Oct 31, 8:06 am, Adam B. [email protected]