Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,36 @@ ContactFilter.new.filter(Contact, 'email:foo@bar.com').to_sql
# => "SELECT * FROM contacts WHERE email='foo@bar.com'"
```

Filter aliases
--------------

You can define aliases for the same filter by passing multiple field names to a single `filter` call:

```ruby
class ContactFilter
include Minidusen::Filter

filter :email, :mail, :contact do |scope, email|
scope.where(email: email)
end
end
```

Now you can search using any of the defined aliases:

```ruby
ContactFilter.new.filter(Contact, 'email:foo@bar.com').to_sql
# => "SELECT * FROM contacts WHERE email='foo@bar.com'"

ContactFilter.new.filter(Contact, 'mail:foo@bar.com').to_sql
# => "SELECT * FROM contacts WHERE email='foo@bar.com'"

ContactFilter.new.filter(Contact, 'contact:foo@bar.com').to_sql
# => "SELECT * FROM contacts WHERE email='foo@bar.com'"
```

This feature is useful when you want to provide multiple intuitive ways for users to search the same field.

### Caveat

If you search for a phrase containing a colon (e.g. `deploy:rollback`), Minidusen will mistake the first part as a – nonexistent – qualifier and return an empty set.
Expand Down
6 changes: 4 additions & 2 deletions lib/minidusen/filter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ module ClassMethods

attr_accessor :minidusen_syntax

def filter(field, &block)
minidusen_syntax.learn_field(field, &block)
def filter(*fields, &block)
fields.each do |field|
minidusen_syntax.learn_field(field, &block)
end
end

end
Expand Down
22 changes: 22 additions & 0 deletions spec/minidusen/filter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -224,4 +224,26 @@ def columns

end

describe 'filter aliases' do

it 'should support defining multiple field aliases with a single filter call' do
filter_class = Class.new do
include Minidusen::Filter

filter :name, :title do |scope, phrases|
scope.where_like([:name] => phrases)
end
end

filter_instance = filter_class.new

match = User.create!(:name => 'John Doe')
no_match = User.create!(:name => 'Jane Smith')

filter_instance.filter(User, 'name:John').to_a.should == [match]
filter_instance.filter(User, 'title:John').to_a.should == [match]
end

end

end