On Oct 31, 9:30 am, Adam Boyle <briefcase.speak... / gmail.com> wrote:
> I accidentally posted this to the RoR forum; my apologies to anyone who
> receives this twice.
>
> 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 (using ActiveRecord-JDBC), 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
> --
> Posted viahttp://www.ruby-forum.com/.

If you're always doing (essentially) "select *", won't Ruby's dbi
work? I don't know if it's guaranteed, but the columns always seem to
be returned in the order they are defined in the database.