Module: BarelySearchable::ModelInjections::ClassMethods
- Defined in:
- lib/barely_searchable/model_injections.rb
Instance Method Summary collapse
- #init_searches_on ⇒ Object
- #search(query, limit = nil) ⇒ Object
- #searches ⇒ Object
- #searches_on(*fields, conditions) ⇒ Object
Instance Method Details
#init_searches_on ⇒ Object
21 22 23 |
# File 'lib/barely_searchable/model_injections.rb', line 21 def init_searches_on @searches = [] end |
#search(query, limit = nil) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/barely_searchable/model_injections.rb', line 29 def search query, limit = nil where = '0' @searches.each do |search_field| field = search_field[0].to_s hash = search_field[1] #check to make sure the field actually exists on the table unless self.columns_hash.include? field raise NameError, "#{field} is not a valid column on #{self}" end #cast the query to the right data type for this column col_query = cast_to_column(query, field) #check for an if-condition next if ! hash[:if].nil? && ! hash[:if].call(col_query) #check for an unless condition next if ! hash[:unless].nil? && hash[:unless].call(col_query) if equality_columns.include? column_to_type(field) where += ' or ' + self.arel_table[field].eq( col_query ).to_sql else like = '%' + col_query.to_s.gsub(' ','%') + '%' where += ' or ' + self.arel_table[field].matches( like ).to_sql end end if limit.nil? self.where( where ) else self.where( where ).limit( limit ) end end |
#searches ⇒ Object
25 26 27 |
# File 'lib/barely_searchable/model_injections.rb', line 25 def searches @searches end |
#searches_on(*fields, conditions) ⇒ Object
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/barely_searchable/model_injections.rb', line 5 def searches_on *fields, conditions if conditions.kind_of? Symbol fields.push conditions conditions = {} end conditions = {} if conditions.nil? if @searches.nil? init_searches_on end fields.map! {|field| [field, conditions]} @searches.push *fields end |