Skip to content

Instantly share code, notes, and snippets.

@lastk
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lastk/499539c8f0b47b5875fa to your computer and use it in GitHub Desktop.
Save lastk/499539c8f0b47b5875fa to your computer and use it in GitHub Desktop.
#model
require 'csv'
class ContatoNews < ActiveRecord::Base
paginates_per 9
validates_format_of :email,
:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,
:message => 'email must be valid'
def self.to_csv_file
#Busca todos os contatos, formata os contatos por um array pra cada linha e insere no csv
CSV.open("#{RAILS_ROOT}/public/contatos.csv","w") do |csv|
#cabecalho1
csv << ["Nome","E-mail"]
#contatos
contatos = ContatoNews.csv_contatos
contatos.each do |contato|
csv << contato
end
end
return "#{RAILS_ROOT}/public/contatos.csv"
end
def self.buscar(pagina=1,key=nil)
key = "" if key == nil
ContatoNews.where("nome like ? or email like ? ",
"%#{key}%", "%#{key}%").page(pagina)
end
protected
def self.csv_contatos()
temp = ContatoNews.all
contatos = []
temp.each do |contato|
contatos << [contato.nome,contato.email]
end
contatos
end
end
def exportar
send_file ContatoNews.to_csv_file
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment