require 'active_record' module FlexaLib module ActiveRecord module PesquisaWrapper # # flexa_search BUSCA # # Model.flexa_search(:search => {:text => params[:search], # :fields => ['nome','cod_cidade']}, :page => params[:page]) # def flexa_search(options) options = options.dup search_options = options.fetch(:search) { raise ArgumentError, ":search is required" } likes_search = search_options.fetch(:fields) { raise ArgumentError, ":fields is required" } text_search = search_options.fetch(:text) { raise ArgumentError, ":text is required" } text_search ||= '' options.delete(:search) if text_search.length > 0 and likes_search.count > 0 likes_search.collect! {|x| "(UPPER("+x+") LIKE UPPER(:search))"} paginate(options).where(likes_search.join(' OR '), :search => "%"+text_search.to_s+"%") else paginate(options) end end end #fim do modulo PesquisaWrapper module Lookup def delegate_lookup(*methods) options = methods.pop unless options.is_a?(Hash) && to = options[:to] raise ArgumentError, "Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, :to => :greeter)." end to = to.to_s prefix, allow_nil = options.values_at(:prefix, :allow_nil) prefix = true if prefix.nil? allow_nil = true if allow_nil.nil? if prefix == true && to =~ /^[^a-z_]/ raise ArgumentError, "Can only automatically set the delegation prefix when delegating to a method." end method_prefix = if prefix "#{prefix == true ? to : prefix}_" else '' end file, line = caller.first.split(':', 2) line = line.to_i methods.each do |method| method = method.to_s # Attribute writer methods only accept one argument. Makes sure []= # methods still accept two arguments. definition = (method =~ /[^\]]=$/) ? "arg" : "*args, &block" if allow_nil module_eval(<<-EOS, file, line - 2) def #{method_prefix}#{method}(#{definition}) # def customer_name(*args, &block) if #{to} || #{to}.respond_to?(:#{method}) # if client || client.respond_to?(:name) #{to}.#{method}(#{definition}) # client.name(*args, &block) end # end end # end EOS else exception = %(raise "#{self}##{method_prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}") module_eval(<<-EOS, file, line - 1) def #{method_prefix}#{method}(#{definition}) # def customer_name(*args, &block) #{to}.#{method}(#{definition}) # client.name(*args, &block) rescue NoMethodError # rescue NoMethodError if #{to}.nil? # if client.nil? #{exception} # # add helpful message to the exception else # else raise # raise end # end end # end EOS end #cria funcao com valor false module_eval(<<-EOS, file, line - 2) def #{method_prefix}#{method}=(val) # def customer_name=(val) false # false end # end EOS #cria funcao com valor false end end end ::ActiveRecord::Base.extend Lookup # adicionar ao ActiveRecord ::ActiveRecord::Base.extend PesquisaWrapper end end