On Sep 16, 2009, at 6:39 AM, Bill Devaul wrote:

>
> I have written the below code in my seed.rb file.  It takes my old  
> data
> in tab delimited format and brings it into the Rails database.
>
> I want to remove the eval statement as I understand there are problems
> with eval.
>
> Any suggestions are appreciated.
>

I'm sure there's a more efficient way of re-mapping the fields, but  
the below should work.

class Plant

   def self.grow (model_name, filename, field_mappings, headers = true)

     the_model = Kernel.const_get(model_name)
     the_model.delete_all

     table = FasterCSV.table(filename, {
       :headers => headers,
       :header_converters => :symbol,
       :col_sep => "\t" # need the double quotes
     })

     table.each do |row|
       mapped_fields = {}
       row.each_pair{|k,v| mapped_fields[field_mappings[k.to_sym]] = v}
       record = the_model.create(mapped_fields)
     end

   end

end


Plant.grow(
   "Business",
   File.join(File.dirname(__FILE__), 'vendor.db'),
   {:address         => :vendoraddress,
    :city            => :vendorcity,
    :email_general   => :vendoremail,
    :fax             => :faxnumber,
    :name            => :vendorname,
    :old_vendorid    => :vendorid,
    :phone           => :vendorphone,
    :sales_tax_rate  => :vendorsalestax,
    :zip_code        => :vendorzipcode},
   true
)















>
> seed.rb
> ---------------------------------------------
> #TODO move require and plant class to helper
> #TODO do not use eval if possible
> require 'FasterCSV'
>
> class Plant
>
>  def self.grow (model, filename, datamap, headers = true)
>
>    Kernel.const_get(model).delete_all
>
>    table = FasterCSV.table(filename, {
>       :headers => headers,
>       :header_converters => :symbol,
>       :col_sep => "\t" # need the double quotes
>       })
>
>    table.each do |row|
>      record = eval datamap
>    end
>
>  end
>
> end
>
>
> Plant.grow(
>  "Business",
>  File.join(File.dirname(__FILE__), 'vendor.db'),
>  "Business.create(
>  :address         => row[:vendoraddress],
>  :city            => row[:vendorcity],
>  :email_general   => row[:vendoremail],
>  :fax             => row[:faxnumber],
>  :name            => row[:vendorname],
>  :old_vendorid    => row[:vendorid],
>  :phone           => row[:vendorphone],
>  :sales_tax_rate  => row[:vendorsalestax],
>  :zip_code        => row[:vendorzipcode]
>  )",
>  true)
> -- 
> Posted via http://www.ruby-forum.com/.
>
> >


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to