Skip to content

Instantly share code, notes, and snippets.

@itay-grudev
Created April 19, 2016 14:17
Show Gist options
  • Save itay-grudev/59ea43a5f993c00db58d3abd66a4b9b4 to your computer and use it in GitHub Desktop.
Save itay-grudev/59ea43a5f993c00db58d3abd66a4b9b4 to your computer and use it in GitHub Desktop.
Rails Video Link Embedding Helper
# Copyright (c) 2016 Itay Grudev
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
module VideoHelper
YOUTUBE_ID_REGEX = /(?:https?:\/\/)?(?:www.)?(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/watch\?feature=player_embedded&v=)([A-Za-z0-9_-]*)(?:\&\S+)?(?:\?\S+)?/
VIMEO_ID_REGEX = /^https?:\/\/(?:.*?)\.?vimeo\.com\/(\d+).*$/
def embed_video(url)
regex = YOUTUBE_ID_REGEX
match = url.match(regex)
if match and match.length == 2
return "<div class='embed-responsive embed-responsive-16by9'><iframe class='embed-responsive-item' width='640' height='390' src='https://www.youtube.com/embed/#{match[1]}'></iframe></div>"
end
regex = VIMEO_ID_REGEX
match = url.match(regex)
if match and match.length == 2
return "<div class='embed-responsive embed-responsive-16by9'><iframe class='embed-responsive-item' width='640' height='390' src='https://player.vimeo.com/video/#{match[1]}?title=0&byline=0&portrait=0&badge=0'></iframe></div>"
end
return nil
end
def validate_video_url(url)
return false if url.blank?
if url.match(YOUTUBE_ID_REGEX).length == 2 or url.match(VIMEO_ID_REGEX).length == 2
return true
end
false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment