Skip to content

Instantly share code, notes, and snippets.

@thelinuxlich
Created August 6, 2010 17:29
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 thelinuxlich/511647 to your computer and use it in GitHub Desktop.
Save thelinuxlich/511647 to your computer and use it in GitHub Desktop.
def datatable_ajax(modelo,opcoes={})
options = {:limit => params[:iDisplayLength], :offset => params[:iDisplayStart], :order => [], :include => []}
conditions = []
tabela_pai = modelo.to_s.tableize
@ordem = criar_array_de_ordenacao
opcoes[:campos].each_with_index do |v,i|
if @ordem.include?(i.to_s)
options[:order] << formatar_campo_ordem(tabela_pai,v,params["sSortDir_#{@ordem.index(i.to_s)}"])
end
includes = include_tabela_campo(v)
options[:include] << includes if includes.present?
if params[:sSearch].present?
pesquisa = pesquisa_tabela_campo(tabela_pai,v)
conditions << pesquisa if pesquisa.present?
end
end
if options[:order].empty?
options.delete(:order)
else
options[:order] = options[:order].join(',')
end
options[:include].flatten!
options[:conditions] = conditions.join(' or ') if conditions.size > 0
scopes = opcoes[:scopes].join('.') if opcoes[:scopes].present?
total_display_records = eval("#{modelo.to_s.camelize}.#{scopes.blank? ? "all" : scopes+".all"}(options).count")
@resource = eval("#{modelo.to_s.camelize}.#{scopes.blank? ? "all" : scopes+".all"}(options)")
render :json => {:sEcho => params[:sEcho].to_i,
:iTotalRecords => eval("#{modelo.to_s.camelize}.#{scopes.blank? ? "all" : scopes+".all"}.count"),
:iTotalDisplayRecords => total_display_records,
:aaData => @resource.map {|r|
valores = []
opcoes[:campos].each do |c|
valores << formatar_valor_para_json(r,c)
end
valores.flatten
}}.to_json
end
private
def criar_array_de_ordenacao
total_campos = params[:iSortingCols].to_i
ordem = []
0.upto(total_campos) do |i|
ordem << params["iSortCol_#{i}"]
end
return ordem
end
def formatar_campo_ordem(tabela,campo,ordem)
campo_formatado = ""
if campo.is_a? Hash
subtabela = campo.keys[0].to_s.tableize
if campo.values[0].to_s == "nome_completo"
campo_formatado = "#{subtabela}.nome #{ordem}, #{subtabela}.sobrenome #{ordem}"
elsif ["atendente","transmissor","receptor"].include?(campo.keys[0].to_s)
campo_formatado = "usuarios.#{campo.values[0].to_s.gsub('_para_exibicao','')} #{ordem}"
elsif chave.to_s == "carro"
campo_formatado = "marcas.nome #{ordem}, carros.modelo #{ordem}"
else
campo_formatado = "#{subtabela}.#{campo.values[0].to_s.gsub('_para_exibicao','')} #{ordem}"
end
else
if campo.to_s == "nome_completo"
campo_formatado = "#{tabela}.nome #{ordem}, #{tabela_pai}.sobrenome #{ordem}"
else
campo_formatado = "#{tabela}.#{campo.to_s.gsub('_para_exibicao','')} #{ordem}"
end
end
campo_formatado
end
def include_tabela_campo(campo)
if campo.is_a? Hash
if campo.keys[0].to_sym == :carro
{:carro => :marca}
else
campo.keys[0]
end
end
end
def pesquisa_tabela_campo(tabela,campo)
if campo.is_a? Hash
formatar_campo_conditions(campo.keys[0].to_s.tableize,campo.values[0],params[:sSearch])
else
formatar_campo_conditions(tabela,campo,params[:sSearch])
end
end
def formatar_valor_para_json(objeto,campo)
valores = []
if campo.is_a? Hash
valor = objeto.try(campo.keys[0].to_sym).try(campo.values[0].to_sym)
valores << formatar_valor(valor)
else
valor = objeto.send(campo)
valores << formatar_valor(valor)
end
valores
end
def formatar_valor(valor)
format_num = Object.new.extend(ActionView::Helpers::NumberHelper)
format_str = Object.new.extend(ActionView::Helpers::TextHelper)
if valor.is_a?(FalseClass) || valor.is_a?(TrueClass)
boolean_view(valor)
elsif valor.is_a?(ActiveSupport::TimeWithZone)
valor.strftime("%d/%m/%Y às %H:%M")
elsif valor.is_a?(Float)
format_num.number_to_currency(valor,:unit => "R$")
elsif valor.is_a?(String)
format_str.truncate(valor,:length => 30)
else
valor ? valor : ""
end
end
def formatar_campo_conditions(tabela,campo,valor)
campo = campo.to_s.gsub('_para_exibicao','')
case campo
when "nome"
if tabela == "carros"
"marcas.nome ilike '%#{valor}%' or "+
"carros.modelo ilike '%#{valor}%'"
else
"#{tabela}.nome ilike '%#{valor}%'"
end
when "nome_completo"
"#{tabela}.nome ilike '%#{valor}%' or "+
"#{tabela}.sobrenome ilike '%#{valor}%'"
when "valor", "id"
if valor =~ /^\d+$/
"#{tabela}.#{campo} = #{valor}"
end
when "servicos"
"servicos.nome ilike '%#{valor}%'"
when "condutor","created_at",/data_/,/_count/
else
"#{tabela}.#{campo} ilike '%#{valor}%'"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment