Skip to content

Instantly share code, notes, and snippets.

@xijo
Created November 28, 2012 23:34
Show Gist options
  • Save xijo/4165555 to your computer and use it in GitHub Desktop.
Save xijo/4165555 to your computer and use it in GitHub Desktop.
Alternative oembed solutions
class OembedTranslator
include ActionView::Helpers::TagHelper
# usual stuff over here..
def embed
@content.gsub(/(?:<a.+?<\/a>)|((?:www|https?).*?)(?=\s|\Z)/) do |match|
match.present? or next # regexp not perfect yet, there are nil matches for some reason
oembed_code_for(match)
end
end
private
def oembed_code_for(link)
response = OEmbed::Providers.get(link, :width => 450, :maxWidth => 450)
response.html
rescue OEmbed::NotFound
link.start_with?("<a") ? link : content_tag(:a, link, href: link)
rescue OEmbed::Error
link
end
end
@xijo
Copy link
Author

xijo commented Nov 28, 2012

Basic idea is: capture all those anchors first, with lower prio then the remaining urls. For each of them there is a answer with what to replace, delivered by the oembed_code_for method.

@xijo
Copy link
Author

xijo commented Nov 29, 2012

Bonus cake for me! harhar It's: /((?:<a.+?</a>)|(?:www|https?).*?(?=\s|\Z))/

@grekko
Copy link

grekko commented Nov 29, 2012

nice one

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment