Skip to content

Instantly share code, notes, and snippets.

@jredville
Created August 12, 2011 19:24
Show Gist options
  • Save jredville/1142780 to your computer and use it in GitHub Desktop.
Save jredville/1142780 to your computer and use it in GitHub Desktop.
Validation options
#this option is more explicit, but not as DRY and flexible
module BaseValidator
def validate_each(rec, attr, val)
#calls one or two known methods
end
end
class AsFooValidator < ActiveModel::EachValidator
include BaseValidator
def foo #one of the known methods
end
end
class Foo < ActiveRecord::Base
validates :foo, :as_foo => { :more_options => here }
end
#this option is more "magical", but it is DRY, and could be more flexible using callbacks
module ValidatorCreator
def self.included(obj)
cls_name = obj.name + "Validator"
newobj = Object.const_set cls_name, Class.new(ActiveModel::EachValidator)
newobj.send(:include, obj)
end
def validate_each(rec, attr, val)
#calls one or two known methods
end
end
module AsFoo
include ValidatorCreator #generates AsFooValidator
def foo #known method
end
end
class Foo < ActiveRecord::Base
validates :foo, :as_foo => { :more_options => here }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment