Class: Pursuit::SimpleSearch
- Inherits:
-
Object
- Object
- Pursuit::SimpleSearch
- Defined in:
- lib/pursuit/simple_search.rb
Overview
Provides an interface for declaring which attributes should be searched in a simple query, and a method for applying a simple query to an ‘ActiveRecord::Relation` instance.
Instance Attribute Summary collapse
-
#attributes ⇒ Set<Arel::Attributes::Attribute>
The attributes to match against.
-
#default_table ⇒ Arel::Table
The default table to retrieve attributes from.
Instance Method Summary collapse
-
#apply(query, relation) ⇒ ActiveRecord::Relation
Applies the simple clauses derived from ‘query` to `relation`.
-
#initialize(default_table: nil, &block) ⇒ SimpleSearch
constructor
Creates a new simple search instance.
-
#parse(query) ⇒ Arel::Nodes::Node
Parse a simple query into an ARel node.
-
#search_attribute(attribute) ⇒ Arel::Attributes::Attribute
Adds an attribute to match against in queries.
Constructor Details
#initialize(default_table: nil, &block) ⇒ SimpleSearch
Creates a new simple search instance.
21 22 23 24 25 26 |
# File 'lib/pursuit/simple_search.rb', line 21 def initialize(default_table: nil, &block) @attributes = Set.new @default_table = default_table instance_eval(&block) if block end |
Instance Attribute Details
#attributes ⇒ Set<Arel::Attributes::Attribute>
Returns The attributes to match against.
10 11 12 |
# File 'lib/pursuit/simple_search.rb', line 10 def attributes @attributes end |
#default_table ⇒ Arel::Table
Returns The default table to retrieve attributes from.
14 15 16 |
# File 'lib/pursuit/simple_search.rb', line 14 def default_table @default_table end |
Instance Method Details
#apply(query, relation) ⇒ ActiveRecord::Relation
Applies the simple clauses derived from ‘query` to `relation`.
61 62 63 64 |
# File 'lib/pursuit/simple_search.rb', line 61 def apply(query, relation) node = parse(query) node ? relation.where(node) : relation.none end |
#parse(query) ⇒ Arel::Nodes::Node
Parse a simple query into an ARel node.
43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/pursuit/simple_search.rb', line 43 def parse(query) value = ActiveRecord::Base.sanitize_sql_like(query) value = "%#{value}%" attributes.inject(nil) do |previous_node, attribute| node = attribute.matches(value) next node unless previous_node previous_node.or(node) end end |
#search_attribute(attribute) ⇒ Arel::Attributes::Attribute
Adds an attribute to match against in queries.
33 34 35 36 |
# File 'lib/pursuit/simple_search.rb', line 33 def search_attribute(attribute) attribute = default_table[attribute] if attribute.is_a?(Symbol) attributes.add(attribute) end |