class SearchableBy::Column

Constants

VALID_MATCH_TYPES

Attributes

attr[R]
match[R]
match_phrase[R]
node[RW]
type[R]
wildcard[R]

Public Class Methods

new(attr, type: :string, match: :all, match_phrase: nil, wildcard: nil) click to toggle source
# File lib/searchable_by/column.rb, line 8
def initialize(attr, type: :string, match: :all, match_phrase: nil, wildcard: nil)
  @attr  = attr
  @type  = type.to_sym
  @match = match
  @match_phrase = match_phrase || match
  @wildcard = wildcard

  raise ArgumentError, "invalid match option #{@match.inspect}" unless VALID_MATCH_TYPES.include? @match
  raise ArgumentError, "invalid match_phrase option #{@match_phrase.inspect}" unless VALID_MATCH_TYPES.include? @match_phrase
end

Public Instance Methods

build_condition(value) click to toggle source
# File lib/searchable_by/column.rb, line 19
def build_condition(value)
  scope = node.not_eq(nil)

  case type
  when :int, :integer
    int_condition(scope, value)
  else
    str_condition(scope, value)
  end
end

Private Instance Methods

escape_term!(term) click to toggle source
# File lib/searchable_by/column.rb, line 60
def escape_term!(term)
  term.gsub!('%', '\%')
  term.gsub!('_', '\_')
  term.gsub!(wildcard, '%') if wildcard
end
int_condition(scope, value) click to toggle source
# File lib/searchable_by/column.rb, line 32
def int_condition(scope, value)
  scope.and(node.eq(Integer(value.term)))
rescue ArgumentError
  nil
end
str_condition(scope, value) click to toggle source
# File lib/searchable_by/column.rb, line 38
def str_condition(scope, value)
  term = value.term.dup
  type = value.phrase ? match_phrase : match

  case type
  when :exact
    if wildcard
      escape_term!(term)
      scope.and(node.matches(term))
    else
      term.downcase!
      scope.and(node.lower.eq(term))
    end
  when :prefix
    escape_term!(term)
    scope.and(node.matches("#{term}%"))
  else # :all (wraps term in wildcards)
    escape_term!(term)
    scope.and(node.matches("%#{term}%"))
  end
end