Assent
Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file lib/assent. To experiment with that code, run bin/console for an interactive prompt.
TODO: Delete this and the text above, and describe your gem
Installation
Add this line to your application's Gemfile:
gem 'assent'
And then execute:
$ bundle
Or install it yourself as:
$ gem install assent
Usage
NOTE: This gem is still under heavy development.
Basic Usage
require 'assent'
# Define a validator that inherits from the assent validator
class LoginValidator < Assent::Validator
field :email, presence: true
field :password, presence: true
end
# instantiate a new instance of the LoginValidator, f.e. in your controller
class LoginController < ApplicationController
def index
validator = LoginValidator.new
if validator.validate(params) #this will return a boolean
# render something
else
#handle validation errors
end
end
end
As you can see above, the validate method accepts the input. Right now, it only accepts a Hash.
Supported validations
- presence
- accepted
- date
- ip
Accessing errors
If the validation failed, you might want to show what went wrong. In that case you can access the errors as follows:
class LoginValidator < Assent::Validator
field :email, presence: true
field :password, presence: true
end
input = Hash.new
input[:email] = ''
validator = LoginValidator.new
validator.validate(input)
validator.errors # This will return {:email => ['The email is required']}
Setting custom error messages
You might want to create your own error messages and luckily you can override the defaults. All you need to do is creating a YAML language file and tell us where to find it.
Inside the YAML file you have access to the field variable. This variable will automatically be replaced with the field the validation is for.
The YAML file should look like this:
presence: This is my custom message for :field
Supported overrides are:
- presence
- accepted
- date
- ip
To load your configuration file, just use the config_file method on Assent::Config:
#some place where your configuration lives
Assent::Config.config_file 'path/to/yaml/file'
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/frankieleef/assent.
License
The gem is available as open source under the terms of the MIT License.