Skip to content

Instantly share code, notes, and snippets.

@tlux
Created August 21, 2012 11:52
Show Gist options
  • Save tlux/3414871 to your computer and use it in GitHub Desktop.
Save tlux/3414871 to your computer and use it in GitHub Desktop.
Combining Addressable::URIs
require 'addressable/uri'
module CombineUri
def combine(other_uri)
dup.combine!(other_uri)
end
def combine!(other_uri)
return self unless other_uri
other_uri = self.class.parse(other_uri) unless self.class == other_uri.class
overwrite_if_set(other_uri, :scheme)
overwrite_if_set(other_uri, :host)
overwrite_if_set(other_uri, :port)
overwrite_if_set(other_uri, :fragment)
merge_path(other_uri)
merge_query_values(other_uri)
self
end
private
def overwrite_if_set(other_uri, method_name)
value = other_uri.send(method_name)
self.send(:"#{method_name}=", value) if value
end
def merge_path(other_uri)
self.path = self.class.join(path, other_uri.path) if other_uri.path
end
def merge_query_values(other_uri)
if query_values or other_uri.query_values
self.query_values = (query_values || {}).merge(other_uri.query_values || {})
end
end
end
Addressable::URI.send :include, CombineUri
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment