下面的代码将采用任何 vimeo 或 youtube URL 并返回视频 ID 和提供者。
在你的模型中
def parse_video_url(url)
@url = url
youtube_formats = [
%r(https?://youtu\.be/(.+)),
%r(https?://www\.youtube\.com/watch\?v=(.*?)(&|#|$)),
%r(https?://www\.youtube\.com/embed/(.*?)(\?|$)),
%r(https?://www\.youtube\.com/v/(.*?)(#|\?|$)),
%r(https?://www\.youtube\.com/user/.*?#\w/\w/\w/\w/(.+)\b)
]
vimeo_formats = [%r(https?://vimeo.com\/(\d+)), %r(https?:\/\/(www\.)?vimeo.com\/(\d+))]
@url.strip!
if @url.include? "youtu"
youtube_formats.find { |format| @url =~ format } and $1
@results = {provider: "youtube", id: $1}
@results
elsif @url.include? "vimeo"
vimeo_formats.find { |format| @url =~ format } and $1
@results = {provider: "vimeo", id: $1}
@results
else
return nil # There should probably be some error message here
end
end
然后在您的控制器中调用:
@results = @course.parse_video_url(@course.video_url)
# Access the hash with @results[:provider] or @results [:id]
在您看来,您可以编写一个 IF 语句来显示提供程序/id 组合的相关嵌入代码。