解决方案:
由于这是一个 Rails 应用程序,我决定使用oembed gem并在显示文本而不是输入文本时解析视频链接。这对我来说是最好的解决方案,因为存储裸视频 URL 比存储 oembed 返回的完整嵌入 iframe 代码并希望它永远不必更改更能证明未来。
这段代码很快就被破解了,需要尽快重构,但它现在运行良好,并且失败对应用程序没有任何影响。
当显示我运行的课程parse_media_embeds
时,lesson.notes
它会找到所有链接,对于任何匹配的媒体站点,它会获取 oEmbed 代码(带有rescue
错误的 a)并用 iframe 替换链接。完全笨拙,但它让我可以继续使用该应用程序。
我会在重构时发布新代码。
查看:课程.html.rb
...
<section class='lesson-notes'>
<p><%= lesson.parse_media_embeds.html_safe %></p>
</section>
...
型号:课程.rb
def parse_media_embeds
# get an array of links in the notes
links = URI.extract self.notes, /http(s)?/
# due to wysihtml5 parsing each link is stored twice, once as url and once as text
# like <a href='http://google.com'>http://google.com</a>
# so remove the double references
for pos in (0..links.count)
link.delete_at(pos)
end
# now replace each link that matches the Regexp pattern with oembed version
links.each do |link|
# only replace links for YouTube, Vimeo and Soundcloud
if link.match(/youtu\.be|youtube|vimeo|soundcloud/)
# get the full link tag, which includes both instances of the link text
string = /(<a\w*[^>]*>#{Regexp.escape(link)}[^<]*<\/a>)/
embed = get_oembed(link)
self.notes = self.notes.gsub(string, embed) if embed
end
end
self.notes
end
型号:课程.rb
def get_oembed(link)
# each provider has a different set of params
if link.match(/youtu\.be|youtube/)
begin
resource = OEmbed::Providers::Youtube.get(link, {maxwidth: 320})
rescue
return
end
resource.html
elsif link.match(/vimeo/)
begin
resource = OEmbed::Providers::Vimeo.get(link, {maxwidth: 320})
rescue
return
end
resource.html
elsif link.match(/soundcloud/)
begin
resource = OEmbed::Providers::SoundCloud.get(link, {color: '39d', show_comments: false})
rescue
return
end
resource.html
else
return
end
end