Skip to content

Instantly share code, notes, and snippets.

@md-farhan-memon
Forked from niquepa/gist:4c59b7d52a15dde2367a
Last active September 3, 2020 17:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save md-farhan-memon/4fa1df2c19e8acec60a9eb2e2e1235b7 to your computer and use it in GitHub Desktop.
Save md-farhan-memon/4fa1df2c19e8acec60a9eb2e2e1235b7 to your computer and use it in GitHub Desktop.
Ruby/Rails generate YouTube or Vimeo embed video ifram from url
class VideoEmbedUrlGenerator
REGEX_ID = %r{(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/|vimeo\.com\/)([a-zA-Z0-9_-]{8,11})}.freeze
REGEX_PROVIDER = /(youtube|youtu\.be|vimeo)/.freeze
def initialize(url)
@url = url
end
def construct_iframe
'<iframe '\
'width="640" '\
'height="480" '\
'frameborder="0" '\
'allow="autoplay; fullscreen" '\
'allowfullscreen, '\
"src='#{construct_url}'>"\
'</iframe>'
end
def construct_url
case video_provider
when :youtube
"https://www.youtube.com/embed/#{video_id}"
when :vimeo
"https://player.vimeo.com/video/#{video_id}"
end
end
private
attr_accessor :url
def video_provider
case matched_result(REGEX_PROVIDER)
when 'youtube', 'youtu.be'
:youtube
when 'vimeo'
:vimeo
end
end
def video_id
matched_result(REGEX_ID)
end
def matched_result(regex)
match = regex.match(url)
return if match.blank? || match[1].blank?
match[1]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment