Skip to content

Allowing users to post youtube videos to your Ruby on Rails web app

Posted on 12 April 2008

This method allows your users to post youtube videos without exposing yourself to the vulnerabilities of them pasting in any script they like.

They can paste in either the embed code or the url for a video page and we will store this in the database and write a method on the model to extract the relevant video ID and then build the youtube embed code on the page ourselves.

Enough chat here's the ruby. Note that the database field we store the original user pasted code is called 'video code'

require 'hpricot'
class Video < ActiveRecord::Base
 def video_id
    unless video_code.nil?    
      # Check whether Youtube embed code was entered
      doc = Hpricot.parse(video_code)
    
      #Check if there is a movie param
      embed_url = if (element = doc % "//param[@name='movie']")
        element.attributes["value"]
      elsif (element = doc % "//embed") #Check for the movie code in the embed element
        element.attributes["src"]
      end
    
      #If we have pulled out a URL from the embed code, get the v param
      if embed_url && (match = %r{/v/(\w+)&}.match(embed_url))
        return match[1]
      end
    
      #If the user entered the video page url
      query_string = video_code.split( '?', 2)[1]
      if query_string
        params = CGI.parse(query_string)
        if params.has_key?("v")
          return params["v"][0]
        end
      end
    end
  end
end

Note that you need the hpricot gem to parse the text entered by the user.

sudo gem install hpricot

We can then use the video_id method to pull out the id and generate the youtube code safely...

<div class="youtube_video">
    <object width="425" height="355">
        <param name="movie" value="http://www.youtube.com/v/#{video_id}&hl=en"></param>
        <param name="wmode" value="transparent"></param>
        <embed src="http://www.youtube.com/v/#{video_id}&hl=en" type="application/x-shockwave-flash" wmode="transparent" width="425" height="355"></embed>
    </object>
</div>

View the snippets archive ››

No comments have been left

Got something to say?

About

Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.

Contact

my name at gmail.com

More snippets

Take a look in the archive

Need a website?

Contact my employer. Make sure to check out our portfolio of work.

Hosting

I recommend hostingrails.com