DuckForm - QUACK
I found it annoying that the form_for
method of building forms only worked with models. DuckForm creates a way to
build arbitrary models so you can consistently use the form_for
method to build forms throughout your Rails application.
Good examples of this are search forms, or login forms.
This can also be useful to hide nastly implementation details for form input that touches multiple models.
For example, you have an Account and User and UserRole models.
When a user registers, you want to create a new Account and add a role of 'admin' to the Account for that User.
You can ask for all of the User and Account details in one form, and implement a #save
method on the Registration DuckForm that handles all of these details.
Much better than cluttering up your User model with registration specific callback methods.
Installation
Add this line to your Rails application's Gemfile:
gem 'duck_form'
And then execute:
$ bundle
Usage
Create Concrete Classes
Simply extend the DuckForm class, and add attributes. ActiveModel::Validations
is included for free!
class Registration < DuckForm
attr_accessor :email, :password, :password_confirmation, :account_name
validates :email, :password, :account_name, presence: true
validates :password, confirmation: true
end
On-the-Fly
You can build your own DuckForms on the fly, for simple cases using DuckForm.build(name, \*attributes, &block)
Use a Has to define attributes with default values.
Also, if you pass a block, it will be class_eval
ed so you can define additional methods for your DuckForm.
# in a controller
class SearchesController < ApplicationController
def search_form
DuckForm.build "Search", :query, max_results: 10 do
def search
Product.search(query, limit: max_results)
end
end
end
helper_method :search_form
def create
search_form.update_attributes(params[:search])
results = search_form.search
respond_with results
end
end
# in a view (haml)
= form_for search_form do |f| # will POST to /searches, override the URL if you'd like
= f.label :query
= f.text_field :query
= f.label :max_results
= f.number_field :max_results
= f.submit
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request