Converting a regular Youtube 'link' into an embedded video

前端 未结 10 1853
别那么骄傲
别那么骄傲 2021-01-30 02:25

My goal: I am trying to allow users to embed a link to a Youtube video in my site, while giving me control over the player\'s settings.

I would like to do this by only a

10条回答
  •  一个人的身影
    2021-01-30 03:08

    I have created a simple helper to embed YouTube videos:

    # Helpers for better embedding and manipulation of videos
    module VideosHelper
      # Regex to find YouTube's video ID
      YOUTUBE_REGEX = %r(^(http[s]*:\/\/)?(www.)?(youtube.com|youtu.be)\/(watch\?v=){0,1}([a-zA-Z0-9_-]{11}))
    
      # Embeds YouTube video of given URL in an iframe
      #
      # @param url [String] URL of desired video
      # @param width [String] width of embedded video. Can be any valid CSS unit
      # @param height [String] height of embedded video. Can be any valid CSS unit
      # @return [String] HTML string of embedded video
      def youtube_embed(url, width = "100%", height = "250px")
        youtube_id = find_youtube_id(url)
    
        result = %()
        result.html_safe
      end
    
      # Finds YouTube's video ID from given URL or [nil] if URL is invalid
      # The video ID matches the RegEx \[a-zA-Z0-9_-]{11}\
      #
      # @param url [String] URL of desired video
      # @return [String] video ID of given URL
      def find_youtube_id(url)
        url = sanitize(url).to_str
    
        matches = YOUTUBE_REGEX.match url
    
        if matches
          matches[6] || matches[5]
        end
      end
    end
    

提交回复
热议问题