Created
August 12, 2011 19:24
-
-
Save jredville/1142780 to your computer and use it in GitHub Desktop.
Validation options
This file contains 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
#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 file contains 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
#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