Embed vimeo player in Rails?

2019-06-04 03:09发布

问题:

I want to allow users to submit a vimeo url and embed that in a player. Is there a plugin or gem that does that?

Thanks

回答1:

Vimeo has details on how to embed using their API: http://www.vimeo.com/api/docs/oembed

Under their "unofficial downloads" page, there is this gem: http://github.com/matthooks/vimeo



回答2:

Old question but I found myself in the same situation.

If you wan't to retrieve Vimeo iframe for your video you can use the following code. No need to add a gem.

Add helper

Just create a file app/helpers/videos_helper.rb and the following lines.

module VideosHelper

  require 'net/http'

  VIMEO_REGEX = %r(^https?:\/\/(?:.*?)\.?(vimeo)\.com\/(\d+).*$)

  # Finds Vimeo's video ID from given URL or [nil] if URL is invalid
  def find_vimeo_id url
    url     = sanitize url
    matches = VIMEO_REGEX.match url.to_str
    matches[2] if matches
  end

  # Get Vimeo video iframe from given URL
  def get_vimeo_iframe url, width, height
    vimeo_id = find_vimeo_id url
    uri      = "https://vimeo.com/api/oembed.json?url=https%3A//vimeo.com/#{ vimeo_id }&width=#{ width }&height=#{ height }"
    response = Net::HTTP.get( URI.parse( uri ))
    json     = JSON.parse response
    json['html'].html_safe
  end

end

Get iframe in view

In your view just call get_vimeo_iframe() to print the iframe.

<%= get_vimeo_iframe('http://your.vimeo.url') %>

Or if you want you can add width and height

<%= get_vimeo_iframe('http://your.vimeo.url', '800px', '450px') %>

If you want I created this gist which lets you ask also for YouTube iframe (not just Vimeo).