Rails - Regex inside a method used for validations
I have a validation that checks the format of a url using regex. I was wondering if it's possible to put the regex inside of a method:
validates_format_of :table_name :with开发者_高级运维 => /^(http|https):\/\/[a-z0-9]+([_-.]{1}[a-z0-9]+).[a-z]{2,5}(:[0-9]{1,5})?(\/.)?$/ix
How do I put that regex in a method and use it with the validation?
If you wish to tidy up code without creating a custom validation, then use a constant rather than a method to store the regex.
class Product < ActiveRecord::Base
URL_REGEX = /^(http|https):\/\/[a-z0-9]+([\_\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix
validates_format_of :table_name :with => URL_REGEX
end
It'll work with any class method, or variable/constant that's already defined. But why don't you create a new validator?
# config/initializers/my_validators.rb
ActiveRecord::Base.class_eval do
def self.validates_url_of(attr_name, n, options={})
validates_format_of attr_name, :with => /^(http|https):\/\/[a-z0-9]+([_-.]{1}[a-z0-9]+).[a-z]{2,5}(:[0-9]{1,5})?(\/.)?$/ix
end
end
Then:
class Foo < ActiveRecord::Base
validates_url_of :attribute
end
See http://guides.rubyonrails.org/active_record_validations_callbacks.html#creating-custom-validation-methods
I recommend you take a look at Ruby - Validate and update URL for a much better validation method than regex.
If you're desperate to use Regex, then take a look at this writeup from John Gruber for something much more valuable than the above.
精彩评论