Skip to content

Latest commit

 

History

History
98 lines (69 loc) · 2.67 KB

README.md

File metadata and controls

98 lines (69 loc) · 2.67 KB

PrettyValidation

Gem Version Build Status Code Climate codecov.io Inline docs

"Make validations DRY"

You need not write validations generated by database schema.

Features

  1. generate validation modules from database schema to app/validations/ directory
  2. automatically includes validation module into corresponding model

Installation

Add this line to your application's Gemfile:

gem 'pretty_validation'

And then execute:

$ bundle

Or install it yourself as:

$ gem install pretty_validation

Usage

You can generate validation modules in two ways.

  • run the db:migrate task, and then automatically generates the modules.
  • run the validation:generate task

Note: The module is overwritten each time the task.

Examples

# db/migrate/20151105090101_create_users.rb
class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name, null: false
      t.integer :age, null: false
      t.boolean :admin

      t.timestamps null: false
    end
    add_index :users, :name, unique: true
  end
end

# app/validations/user_validation.rb
module UserValidation
  extend ActiveSupport::Concern

  included do
    validates :name, presence: true
    validates :age, presence: true, numericality: true
    validates_uniqueness_of :name
  end
end

# app/models/user.rb
class User < ActiveRecord::Base
end

And run rails console:

Loading development environment (Rails 4.2.4)
irb(main):001:0> user = User.new
=> #<User id: nil, name: nil, age: nil, admin: nil, created_at: nil, updated_at: nil>
irb(main):002:0> user.valid?
  User Exists (0.1ms)  SELECT  1 AS one FROM "users" WHERE "users"."name" IS NULL LIMIT 1
=> false
irb(main):003:0> p user.errors.full_messages
["Name can't be blank", "Age can't be blank", "Age is not a number"]
=> ["Name can't be blank", "Age can't be blank", "Age is not a number"]

Supported versions

  • Ruby 2.1.x, 2.2.x
  • Rails 4+

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/sinsoku/pretty_validation.