Created
November 4, 2014 20:29
-
-
Save nunosilva800/27b258460a6709ec0458 to your computer and use it in GitHub Desktop.
ensure uri fields have a valid protocol. HTTP by default
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
module Concerns::URIField | |
extend ActiveSupport::Concern | |
included do | |
def self.ensure_valid_protocol_in_uri(field, default_protocol = "http", protocols_matcher="https?") | |
define_method "#{field}=" do |new_uri| | |
if new_uri.present? and not new_uri =~ /^#{protocols_matcher}:\/\// | |
new_uri = "#{default_protocol}://#{new_uri}" | |
end | |
super(new_uri) | |
end | |
end | |
end | |
end | |
# Usage in models: | |
# include Concerns::URIField | |
# ensure_valid_protocol_in_uri :some_link |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment