No commit activity in last 3 years
No release in over 3 years
An ActiveModel validation for checking if an attribute's values are a subset of another set.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.0
~> 1.5.1
= 2.8.0

Runtime

>= 3.0.3
 Project Readme

subset_validator¶ ↑

Description¶ ↑

An ActiveModel validation for checking if an attribute’s values are a subset of another set.

In other words, check that an array is a subset of another array, a hash is a subset of another hash, etc.

Usage Example¶ ↑

Say you have a User model, and each user can have multiple roles, like this:

class User
  attr_accessor :roles

  @@valid_roles = %w(admin manager developer)

  def initialize(roles)
    raise ArgumentError, 'The roles must be an array.' unless roles.is_a? Array

    @roles = roles
  end
end

You probably want your model to prevent arbitrary roles from being assigned. Eg:

the_boss = User.new %w(admin manager bonehead)

One solution is to write a custom setter method that checks if each element of the roles array is contained in @@valid_roles . That’s a pain in the ass, especially if you need to do it more than once.

Enter SubsetValidator:

require 'active_model'
require 'subset_validator'

class User
  include ActiveModel::Validations

  attr_accessor :roles

  @@valid_roles = %w(admin manager developer)

  validates :roles, :subset => {:in => @@valid_roles}

  def initialize(roles)
    raise ArgumentError, 'The roles must be an array.' unless roles.is_a? Array

    @roles = roles
  end
end

That one validation takes care of it all for you:

the_boss = User.new %w(admin manager bonehead)
 => #<User:0x91e4aac @roles=["admin", "manager", "bonehead"]>

the_boss.valid?
 => false
the_boss.errors
 => {:roles=>["contains an invalid value"]}

the_boss.roles = %w(admin manager)
 => ["admin", "manager"]
the_boss.valid?
 => true

SubsetValidator works on more than just arrays, too. In fact, it’ll work on anything, provided that:

  • the attribute’s value can be anything that responds to #each ;

  • the set of valid values can be anything that responds to #include? .

Contributing to subset_validator¶ ↑

  • Check out the latest master to make sure the feature hasn’t been implemented or the bug hasn’t been fixed yet

  • Check out the issue tracker to make sure someone already hasn’t requested it and/or contributed it

  • Fork the project

  • Start a feature/bugfix branch

  • Commit and push until you are happy with your contribution

  • Make sure to add RSpec specs for it. This is important so I don’t break it in a future version unintentionally.

  • Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate that to its own commit so I can cherry-pick around it.

Copyright © 2010 Nick Hoffman. See LICENSE.txt for further details.