No commit activity in last 3 years
No release in over 3 years
Validate specific value for Rails
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 0.5.2
~> 1.1.3
>= 0

Runtime

< 6.0, >= 4.2
 Project Readme

validate_specific_value

Build Status Gem Version

This is a way to validate single attribute in Rails. 🎉

Sometimes there are validations that are quite expensive (e.g. validations that need to perform database queries). In that case you need to avoid using valid? because it simply does a lot more than you need. link

Getting Started

Add this line to your application’s Gemfile:

gem 'validate_specific_value'

Add a validation rule to your model.

validates :name, uniqueness: true

And use:

class User < ApplicationRecord
  validates_specific :name
end

Accessor Methods

Instance context:

user = User.new(name: 'duplicate_name')
user.valid_name?
# => false

user.errors[:name]
# => ["has already been taken"]

Class context:

User.valid_name?('duplicate_name')
# => false

Implementation

The implementation is quite simple.

class User < ApplicationRecord
  def valid_name?
    errors.clear
    self.class.validators_on(:name).each do |validator|
      validator.validate_each(self, :name, self[:name])
    end
    errors.empty?
  end
end

Contributing

Everyone is encouraged to help improve this project. Here are a few ways you can help: