Last active
March 3, 2016 00:57
-
-
Save danielfone/c2d65164c617ef38f051 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'active_model' | |
# | |
# The reusable validator | |
# | |
class PermittedKeysValidator < ActiveModel::EachValidator | |
def check_validity! | |
raise ArgumentError, "you must supply permitted keys" unless permitted_keys.present? | |
end | |
def validate_each(record, attribute, value) | |
value.assert_valid_keys *permitted_keys | |
rescue ArgumentError => e | |
record.errors.add attribute, e.message | |
end | |
private | |
def permitted_keys | |
Array(options[:in]) | |
end | |
end | |
# | |
# Your actual model | |
# | |
class Foo | |
include ActiveModel::Model | |
attr_accessor :my_hash | |
validates :my_hash, permitted_keys: [:foo, :bar] | |
end | |
# | |
# Example | |
# | |
f = Foo.new(my_hash: {baz: 1}) # => #<Foo @my_hash={:baz=>1}> | |
f.valid? # => false | |
f.errors.full_messages # => ["My hash Unknown key: :baz. Valid keys are: :foo, :bar"] | |
f = Foo.new(my_hash: {bar: 1}) # => #<Foo @my_hash={:bar=>1}> | |
f.valid? # => true |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'active_model' | |
class Foo | |
include ActiveModel::Model | |
attr_accessor :my_hash | |
validate :valid_keys | |
private | |
def valid_keys | |
@my_hash.assert_valid_keys :foo, :bar | |
rescue ArgumentError => e | |
errors.add :my_hash, e.message | |
end | |
end | |
f = Foo.new(my_hash: {baz: 1}) # => #<Foo @my_hash={:baz=>1}> | |
f.valid? # => false | |
f.errors.full_messages # => ["My hash Unknown key: :baz. Valid keys are: :foo, :bar"] | |
f = Foo.new(my_hash: {bar: 1}) # => #<Foo @my_hash={:bar=>1}> | |
f.valid? # => true | |
# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment