Skip to content

Instantly share code, notes, and snippets.

@danielfone
Last active March 3, 2016 00:57
Show Gist options
  • Save danielfone/c2d65164c617ef38f051 to your computer and use it in GitHub Desktop.
Save danielfone/c2d65164c617ef38f051 to your computer and use it in GitHub Desktop.
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
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