Repository is archived
No commit activity in last 3 years
No release in over 3 years
A library for creating PORO validators that are composable and can be used with ActiveRecord or standalone.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.3
>= 0
~> 2.13

Runtime

~> 1.0
~> 1.0
 Project Readme

StandaloneValidator

Build Status

A library for creating PORO validators that are composable and can be used with ActiveRecord or standalone.

Installation

Add this line to your application's Gemfile:

gem 'standalone_validator'

And then execute:

$ bundle

Or install it yourself as:

$ gem install standalone_validator

Usage

require 'standalone_validator'

class NameLengthValidator < StandaloneValidator
  def initialize(min_length, attribute_name = :name)
    @min_length = min_length
    @attribute_name = attribute_name
  end

  include_validation do |object, result|
    if object.send(attribute_name).length < @min_length
      result.add_violation(attribute_name, 'should be bigger')
    end
  end

private

  attr_reader :attribute_name
end

class AllNamesValidator < StandaloneValidator
  include_validation NameLengthValidator, 5
  include_validation NameLengthValidator, 4, :last_name
end


Person = Struct.new(:name, :last_name)
validator = AllNamesValidator.new

person = Person.new("Renato", "Zannon")
puts validator.violations_of(person).any? # false

other_person = Person.new("Renato", "Foo")
puts validator.violations_of(other_person).any? # true

validator.violations_of(other_person).each do |violation|
  puts violation.attribute.inspect # :last_name
  puts violation.message.inspect   # "should be bigger"
end

Contributing

  1. Fork it
  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 new Pull Request