Skip to content

Instantly share code, notes, and snippets.

@nunosilva800
Created November 4, 2014 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nunosilva800/27b258460a6709ec0458 to your computer and use it in GitHub Desktop.
Save nunosilva800/27b258460a6709ec0458 to your computer and use it in GitHub Desktop.
ensure uri fields have a valid protocol. HTTP by default
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