Skip to content

Commit

Permalink
adds specified attributes feature
Browse files Browse the repository at this point in the history
  • Loading branch information
kwanso-abdullah committed Aug 7, 2017
1 parent 57c27aa commit 447c2b4
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 3 deletions.
21 changes: 18 additions & 3 deletions lib/ruby_simple_search.rb
Expand Up @@ -30,9 +30,12 @@ def simple_search(search_term, options={}, &block)

patterned_text = "#{@simple_search_pattern.gsub('q', search_term.try(:downcase))}"

@simple_search_attributes.each do |attr|
sql_query_condition << set_sql_query_condition(attr, sql_query_condition)
sql_query_values << patterned_text

if options[:attributes].nil?
sql_query_values, sql_query_condition = search_attributes(@simple_search_attributes, patterned_text)
else
attr = *options[:attributes]
sql_query_values, sql_query_condition = search_attributes(attr, patterned_text)
end

if block.is_a? Proc
Expand Down Expand Up @@ -83,5 +86,17 @@ def set_sql_query_condition(attr, sql_query_condition)
" OR LOWER(#{self.table_name}.#{attr.to_s}) LIKE ?"
end

def search_attributes(attributes, patterned_text)
sql_query_condition = ""
sql_query_values = []

attributes.each do |attr|
sql_query_condition << set_sql_query_condition(attr, sql_query_condition)
sql_query_values << patterned_text
end

[sql_query_values, sql_query_condition]
end

end
end
3 changes: 3 additions & 0 deletions spec/spec_helper.rb
Expand Up @@ -13,6 +13,9 @@
User.create :email => "bob@example.com",
:name => "bob", :address => "usa",
:contact => "56789", :age => 26
User.create :email => "bob@something.com",
:name => "bob", :address => "uk",
:contact => "45786", :age => 21
end

config.after(:all) do
Expand Down
22 changes: 22 additions & 0 deletions spec/user_spec.rb
Expand Up @@ -111,6 +111,28 @@
end }.to raise_error(RubySimpleSearch::Errors::INVALID_TYPE)
end
end

context "with specified attributes" do
it "searches user with email containing 'example'" do
users = User.where("email like ?", '%example%')
User.simple_search_attributes :name, :contact, :address #whatever, doesn't matter
searched_users = User.simple_search('example', {pattern: :containing, attributes: [:email]})
expect(users.count).to eq(searched_users.count)
end

it "searches user with contact containing '45'" do
users = User.where("contact like ?", '%45%')
searched_users = User.simple_search('45', pattern: :containing, attributes: :contact)
expect(users.count).to eq(searched_users.count)
end

it "searches user with name or address containing 'a'" do
users = User.where("name like ? OR address like ?", '%a%', '%a%')
searched_users = User.simple_search('a', pattern: :containing, attributes: [:name, :address])
expect(users.count).to eq(searched_users.count)
end
end

end
end

Expand Down

0 comments on commit 447c2b4

Please sign in to comment.