Created
November 4, 2015 13:45
-
-
Save dobryakov/dc7637abba123e64c166 to your computer and use it in GitHub Desktop.
flexible url sanitizer
This file contains hidden or 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
module UrlSanitizer | |
extend ActiveSupport::Concern | |
require 'uri' | |
# this concern creates a 'virtual' method, for example 'site_url=(arg)', | |
# which validates and sanitizes url by metaprogramming magic | |
# usage in model: | |
# include UrlSanitizer | |
# validates :site_url, :url => {:allow_nil => true} # gem 'validate_url' | |
# after_initialize do | |
# sanitize_url :site_url | |
# end | |
def create_method(name, &block) | |
self.class.send(:define_method, name, &block) | |
end | |
def sanitize_url(attribute_name) | |
method_name = (attribute_name.to_s + '=') | |
create_method(method_name) { |arg| | |
sanitized_value = arg | |
if sanitized_value.to_s.length > 0 | |
if sanitized_value.scan(URI.regexp).count < 1 | |
sanitized_value = 'http://' + sanitized_value | |
end | |
end | |
write_attribute(attribute_name.to_sym, sanitized_value) | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment