Filch
Welcome to Filch! Filch is an easy-to-use, customizable, advanced form builder for Ransack With Filch, you just set up the template, Filch builds the form, and Ransack does the rest! Ransack is a very useful search gem. See their github page. ransack[https://github.com/activerecord-hackery/ransack] At the very least, this can be a guide to some of Ransack's features.
Installation
Add this line to your application's Gemfile:
gem 'filch'
And then execute:
$ bundle
Or install it yourself as:
$ gem install filch
Usage
Quick Usage
Filch requires ransack's advanced search routes to be setup
# config/routes.rb
resources :your_model do
collection do
match 'search' => 'your_model#your_controller_method', via: %i[get post], as: :search
end
end
In your controller:
@q = Filch.ransack_plus(YOUR_MODEL, (params[:q]))
And in your view:
=render('filch/filch', filch: Filch.templates(YOUR_MODEL), button_name: 'Search', results_p: search_YOURMODEL_path)
This will render a search button to show a search form with the default configuration.
Configuration
This gem is entirely built on the Ransack gem. Read the docs there. ransack[https://github.com/activerecord-hackery/ransack]
At the very least this can be a useful guide for ransack, a very useful search gem.
Consider the following Model:
class HumanResource < ApplicationRecord
has_many :underlings, class_name: 'HumanResource', foreign_key 'boss'
belongs_to :boss, class_name: 'HumanResource', optional: true
scope :position, ->(title) { where(title: title) }
scope :retired, -> { where(retired: 1) }
end
HumanResource has the schema:
t.string "name"
t.string "title"
t.big_int "boss_id"
t.integer "retired"
t.string "skills", default: [], array: true
The Array skills, of course, requires a compatible database. Here we're using postgres.
Filch sees Ransack as implementing three kinds of querys.
- Attributes ransackable_attributes are essentially the databases columns. In this case [:name, :title, :boss_id, :retired, :skills]
- Associations ransackable_associations are the model associations. In this case [:boss]
- Scopes ransackable_scopes are not automaticly defined, but need an extra method in your model.
Ransack uses Arel predicates to create its querys. a list of Ransack predicates can be found here[] a list of Arel predicates can be found here[] custom predicates will be described later.
Filch uses templates to build the form(s) as desired. The tempaltes can be named whatever you wish, of course, but for this example we will use 'basic_template' and 'advanced'. References to an undefined template will use a default configuration.
Templates
Filch builds the forms off of user-defined methods in the model. Name the templates in a #templates method.
class HumanResource < ApplicationRecord
...
def self.templates
%i[basic, all]
end
end
If more then one template is listed, Filch will provide a select tag to choose which form-template to show. Without any further configuration, Filch will build the templates with defaults.
Attributes
Ransack expects the query object name for an attribute to be in the following format: attribute_predicate, e.g.
f.search_field('name_eq')
Ransack will use this query to return every entry from the HumanResource model where name equals the given name.
Filch builds its forms using partials. The partial for the 'eq' predicate can found here[]. You can easily override these partials by creating your own. In this case the file app/views/filch/_eq.html.haml will override the default. In the built-in '_eq.html.haml' you will notice the option datalist_id This links the dropdown datalist options to a datalist tag. More on this later.
Which attributes with which predicates Filch will show in the form is configurable in the model. By default it will show all attributes, with a default collection of predicates. To do this add a method to the model:
# arrays of which attributes to build
# this is kept as a separate array to allow predefined sorting
def self.filch_attrs
{
basic_template: %i[name title retired],
advanced: %i[name title boss_id retired]
}
end
def self.filch_attributes
{
basic_template: {
name: %w[eq cont distinct],
title: %w[eq]
}
}
end
Associations
Ransack expects the query object name for an association to be in the following format: association_attribute_predicate, e.g.
f.search_field('underlings_name_eq')
Ransack will use this query to return every entry from the HumanResource model where an underling's name equals the given name.
Filch will again use relevant partials as described above, in Attributes.
Which associations with which attiribute and predicates Filch will show in the form is confiugrable in the model, similar to Attributes.
def self.filch_assoc_keys
{
basic_template: %i[underlings boss]
}
end
# notice the nested hashes here
def self.filch_associations
{
basic_template: {
underlings: {
name: %w[eq]
}
}
}
end
Scopes
As mentioned earlier, Ransack requires ransackable_scopes to be defined in the model:
def self.ransackable_scope(auth_obj = nil)
%w[retired position limit order]
end
Scopes do not use a predicate, instead, Filch will by default use a check box, to decide if ransack should use the scope. This works great for scopes like retired. For a scope like postion that takes a parameter Filch will require the creation of a relevant partial.
app/views/filch/_position.html.haml:
%td
Postion
%td
=f.select(scope_name, %w[Clerk ShiftManager StoreManager Executive])
of course, you can user erb if you prefer.
Filch does have built-in order and limit partials. The order partial uses a select box, options are the model's columns, in this case: name, title, boss_id, retired, and skills. Limit is a number field, to limit the results. 0 returns all. 1 returns 2, as a workaround for Ransack's only returning one element instead of a collection when limited to 1. Limit and Order do not have to be defined on the model, as Rails created those methods for you.
Default Values
Default values per template can be assigned in the model.
def self.filch_defaults
{
basic: {
positon_eq: 'Clerk'
}
}
end
html attributes
Filch can be further customized by assigning html_attributes in the model. This is not per template, but rather will apply to all forms. For example, if you do not like that associations start off hidden, the javascript load 'toggleShowHide' can be removed as follows:
def self.filch_html_attrs
{
assocs: { load: nil }
}
end
If you do not want the datalists to update:
datalist: { class: 'off' }
The default html_attributes are merged with html_attributes assigned in the model.
Possible filch_html_attrs keys are: attrs: defines the '
' tag starting each attribute assocs: defines the '
' tag starting each association. See the example above. button: defines the clickable button that show/hides filch. datalist: defines the datalists. field: defines the fields. label: defines the '
Custom Ransackers and Custom Predicates
Ranack allows for the creation of custom ranasackers. Put them in 'config/initializers/ransack.rb'. They can get messy.
Filch has added three custom ransackers: like, array_cont, and array_not_cont
The like predicate is for postgres. By default the cont predicate in Arel uses ilike with postgres, which is case-insensitive. Nice of them, but case-insensitive is slow, so should be avoided when possible. A search_field using the like predicate would look like:
=f.text_field("#{attr}_like", {list: datalist_id, class: 'js', input: "filchDataList"})
Of course, a Filch configuration referencing a like predicate will do this automaticly.
The array_cont and array_not_cont predicates were similarly build for postgres. They may work for other databases with an array type. The predicate array_cont will translate to
WHERE foo = ANY();
The array_not_cont will translate to:
WHERE foo DOES NOT CONT All();
Datalist
A Filch form features datalists to create a dropdown list of options in the form element. The datalist does not require any configuration. Filch uses javascript to rebuild the datalist on-the-fly. If you want the datalist in your custom form element, add the list option to your helper. As an example, from the built-in search partial:
=f.text_field("#{attr}", {list: datalist_id, class: 'js', input: "filchDataList"})
attr and datalist_id are passed to your partial from the built-in form partial. attr is the name of the attribute. datalist_id is the id of the relevant datalist. If you do not want the datalist to change 'onInput' (e.g. for an eq predicate, where updating as you type would be foolish) remove the input option. If you do not want the datalist (e.g. for a select box, or a number) remove all the options. Updates are turned off while waiting for the results, to keep from hammering the server.
The speed of the updates depends of course on the size of the database and the quality of the indexes.
Results
With Ransack the controller looks something like this:
def search
@q = YOUR_MODEL.ransack(params[:q])
@results = @q.result(@q)
end
With Filch the controller looks something like:
def search
filch = Filch.ransack_plus(YOUR_MODEL, params[:q])
@q = filch.q
@results = filch.results
end
Alternatively, if you don't need filch's ransack_plus results:
def search
filch = Filch.ransack_plus(YOUR_MODEL, params[:q])
@q = filch.q
@results = @q.result
end
Ransack plus adds methods for workarounds
limit: when using limit as a scope, submitting '1' returns true and '0' false. Which is no good as the scope requires an argument. So '1' gets turned into '2' and '0' deletes the parameter, removing the limit scope, and will return all results.
Development
After checking out the repo, run bin/setup
to install dependencies. Then, run rake test
to run the tests. You can also run bin/console
for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install
. To release a new version, update the version number in version.rb
, and then run bundle exec rake release
, which will create a git tag for the version, push git commits and tags, and push the .gem
file to rubygems.org.
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/filch. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
License
The gem is available as open source under the terms of the MIT License.
Code of Conduct
Everyone interacting in the Filch project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.