Sha256: 9d1b240451aa9f90750b2b5b56323c02e4ed620cdeb661d991119baaf797dfbb

Contents?: true

Size: 1.64 KB

Versions: 24

Compression:

Stored size: 1.64 KB

Contents

module Manage
  module Fields
    class Searcher
      class << self
        def generate_search_object(resource_class, search_fields)
          search_class = Class.new do
            include SearchObject.module(:model, :sorting)

            def escape_search_term(term)
              "%#{term.gsub(/\s+/, '%').gsub('.', '_')}%".downcase
            end

            def parse_date(date)
              Date.strptime(date, '%Y-%m-%d') rescue nil
            end
          end


          search_class.scope { resource_class.all }
          Object.const_set("#{resource_class.name.gsub(/:/, '')}Searcher", search_class)

          search_fields.select {|f| not f.to_s.include?('.')}.each do |field|
            field_type = resource_class.columns_hash[field.to_s].type
            case field_type
            when *[:text, :string]
              search_class.option field.to_sym do |scope, value|
                value.blank? ? scope : scope.where("lower(#{field.to_s}) LIKE lower(?)", escape_search_term(value))
              end
            when :datetime
              search_class.option field.to_sym do |scope, value|
                date = parse_date value
                scope.where("DATE(#{field.to_s}) >= ?", date) if date.present?
              end
            when :integer
              search_class.option field.to_sym
            when :boolean
              search_class.option field.to_sym
            else
              search_class.option field.to_sym do |scope, value|
                scope.where "#{field.to_s} = '?'", escape_search_term(value)
              end
            end
          end

          search_class
        end
      end
    end
  end
end

Version data entries

24 entries across 24 versions & 1 rubygems

Version Path
manage-1.4.3 lib/manage/fields/searcher.rb
manage-1.4.2 lib/manage/fields/searcher.rb
manage-1.4.1 lib/manage/fields/searcher.rb
manage-1.4 lib/manage/fields/searcher.rb
manage-1.3.52 lib/manage/fields/searcher.rb
manage-1.3.51 lib/manage/fields/searcher.rb
manage-1.3.50 lib/manage/fields/searcher.rb
manage-1.3.49 lib/manage/fields/searcher.rb
manage-1.3.48 lib/manage/fields/searcher.rb
manage-1.3.47 lib/manage/fields/searcher.rb
manage-1.3.46 lib/manage/fields/searcher.rb
manage-1.3.45 lib/manage/fields/searcher.rb
manage-1.3.44 lib/manage/fields/searcher.rb
manage-1.3.43 lib/manage/fields/searcher.rb
manage-1.3.42 lib/manage/fields/searcher.rb
manage-1.3.41 lib/manage/fields/searcher.rb
manage-1.3.40 lib/manage/fields/searcher.rb
manage-1.3.39 lib/manage/fields/searcher.rb
manage-1.3.38 lib/manage/fields/searcher.rb
manage-1.3.37 lib/manage/fields/searcher.rb