Skip to content

Instantly share code, notes, and snippets.

@squadette
Last active August 29, 2015 14:23
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 squadette/a0a115f14087921ec3c9 to your computer and use it in GitHub Desktop.
Save squadette/a0a115f14087921ec3c9 to your computer and use it in GitHub Desktop.
def self.replace_urls (text)
rx = /(https?:\/\/\p{^Space}+)/
components = text.split(rx).map do |str|
if rx =~ str
chopped = ""
extra_url = ""
str.gsub!(/\p{Punct}+\z/) do |trailing|
if !trailing.blank? && trailing[0] == ')' && /[(]/ =~ str
extra_url += ")"
trailing.slice!(0)
end
if !trailing.blank? && trailing[0] == '/'
extra_url += "/"
trailing.slice!(0)
end
chopped = trailing
""
end
str += extra_url
uri = Addressable::URI.parse(str)
if uri
short_url = ActionController::Base.helpers.truncate str, length: 64, omission: "..."
begin
canonical = Addressable::URI.normalized_encode(uri)
rescue
canonical = uri
end
if /\Ahttps?:\/\/mokum.ru\// =~ str
"<a href='#{canonical}'>#{short_url}</a>" + chopped
else
"<a href='#{canonical}' target='_blank'>#{short_url}</a>" + chopped
end
else
str + chopped
end
else
folded_text = CGI.escapeHTML(str)
folded_text.gsub!(/@[a-z0-9][a-z0-9_-]+[a-z0-9]\b/) do |username|
username.slice!(0)
feed = User.find_by(name: username) || Group.find_by(name: username)
if feed
"<a href='/#{username}/'>@#{username}</a>"
else
"@#{username}"
end
end
folded_text
end
end
components.join("")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment