Skip to content

Instantly share code, notes, and snippets.

@ramfjord
Last active February 28, 2019 22:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramfjord/8903bfd6c4d9dbb0cb44866d4a52335e to your computer and use it in GitHub Desktop.
Save ramfjord/8903bfd6c4d9dbb0cb44866d4a52335e to your computer and use it in GitHub Desktop.
Abusing ActiveModel::Validations
class MyParameter::Base < OpenStruct
def initialize(name:, description:, validations: proc {})
@validator = Class.new(Struct.new(:value)) do
include ActiveModel::Validations
instance_eval(&validations)
def self.model_name()
ActiveModel::Name.new(self, nil, "temp")
end
end
end
def validate(value)
v = validator.new(value)
v.validate
v.errors[:value].messages
end
end
MyParameter.new(name: "example_param", description: "here's what I do",
validations: proc { validates_inclusion_of :value, in: [1,2,3] })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment