Advertisement
Guest User

Untitled

a guest
Aug 9th, 2017
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.99 KB | None | 0 0
  1. #################################################
  2. # Archivo: db.rb
  3.  
  4. require 'rubygems'
  5. require 'date'
  6. # Librería de acceso de DBs: ActiveRecord
  7. require 'active_record'
  8.  
  9. ActiveRecord::Base.establish_connection(
  10.     :adapter => 'mysql',
  11.     :host => 'localhost',
  12.     :user => 'xxx',
  13.     :password => 'yyy',
  14.     :database => 'ejemplo_ruby'
  15. )
  16.  
  17.  
  18. #################################################
  19. # Archivo: persona.rb
  20. class Persona  < ActiveRecord::Base
  21.  
  22.   def from_csv(linea)
  23.     self.dni = linea[0]
  24.     self.apellido = linea[1]
  25.     self.nombre = linea[2]
  26.     self.fecha_nacimiento = Date.parse(linea[3])
  27.   end
  28.  
  29.   def edad
  30.     return ((DateTime.now - self.fecha_nacimiento) / 365.25).floor
  31.   end
  32. end
  33.  
  34.  
  35. #################################################
  36. # Archivo: importar.rb
  37.  
  38. #!/usr/bin/ruby
  39. require 'db'
  40. require 'csv'
  41. require 'persona'
  42.  
  43. archivo_csv = File.open('personas.csv')
  44. CSV::Reader.parse(archivo_csv) do |linea|
  45.   o = Persona.new
  46.   o.from_csv(linea)
  47.   o.save
  48. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement