Simple Validations in the Controller
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
lib
spec
.gitignore
.rspec
Gemfile
LICENSE.txt
README.md
Rakefile
controller_validator.gemspec

README.md

ControllerValidator

Simple Validations in the Controller! (Re)Use the familiar ActiveModel::Errors pattern for controller validations, so you already know how this works.

Project ControllerValidator
gem name controller_validator
license MIT
expert support Get help on Codementor
download rank Total Downloads
version Gem Version
dependencies Dependency Status
code quality Code Climate
inline documenation Inline docs
continuous integration Build Status
test coverage Coverage Status
homepage on Github.com
documentation on Rdoc.info
live chat Join the chat at https://gitter.im/pboling/controller_validator
Spread ♡ⓛⓞⓥⓔ♡ on Coderbits, on Coderwall

Installation

Add this line to your application's Gemfile:

gem 'controller_validator'

And then execute:

$ bundle

Or install it yourself as:

$ gem install controller_validator

Usage

See the integration specs!

class ThingController < ApplicationController

  def create

    @thing = Thing.new

    validator = ValidateThingOnCreate.new()
    validator.validate_and_push_errors_to(instance: @thing)

    # So far save has not been called on @thing, no callbacks have been run, the model is not involved at all

    if @thing.errors.any?
      render :new
    else
      if @thing.save
        redirect_to @thing_path(id: @thing.id)
      else
        render :new
      end
    end
  end

end

class ValidateThingOnCreate < ControllerValidator::Validator

  # Rules for creating a new thing
  # 1. There must not be too many things already
  # 2. There must be no Bobs

  attr_accessor :too_many, :no_bobs

  def initialize()
    @too_many = Thing.count > 100
    @no_bobs = Bob.count == 0
    super
  end

  def validate!
    errors.add(:too_many, "must not be true") if !self.too_many
    errors.add(:no_bobs, "must be true") if !self.no_bobs
    errors.blank?
  end

end

Contributing

  1. Fork it ( https://github.com/[my-github-username]/controller_validator/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request