Sha256: 59ffb3098fcc6f0a50a5d75f97abff69be7d8c73ee8db0062b16d3d7c2925514

Contents?: true

Size: 871 Bytes

Versions: 12

Compression:

Stored size: 871 Bytes

Contents

require 'net/http'

module Spina::Embeds
  class Youtube < Base
    attributes :url
    
    heroicon "video-camera"
    
    REGEX = /(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/
    
    validates :url, presence: true, format: {with: REGEX}
    
    def id
      REGEX.match(url).try(:[], 1)
    end
    
    # Get title from Youtube API (remote call)
    def remote_title
      get_youtube_json&.dig("title")
    end
    
    def to_trix_partial_path
      "spina/embeds/youtubes/thumbnail"
    end
    
    private
  
      def get_youtube_json
        uri = URI("https://www.youtube.com/oembed?url=http://youtube.com/watch?v=#{id}&format=json")
        response = Net::HTTP.get(uri)
        begin
          JSON.parse(response)
        rescue
          nil
        end
      end
      
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
spina-2.12.0 app/models/spina/embeds/youtube.rb
spina-2.11.0 app/models/spina/embeds/youtube.rb
spina-2.10.0 app/models/spina/embeds/youtube.rb
spina-2.9.1 app/models/spina/embeds/youtube.rb
spina-2.9.0 app/models/spina/embeds/youtube.rb
spina-2.8.1 app/models/spina/embeds/youtube.rb
spina-2.8.0 app/models/spina/embeds/youtube.rb
spina-2.7.0 app/models/spina/embeds/youtube.rb
spina-2.6.2 app/models/spina/embeds/youtube.rb
spina-2.6.1 app/models/spina/embeds/youtube.rb
spina-2.6.0 app/models/spina/embeds/youtube.rb
spina-2.5.0 app/models/spina/embeds/youtube.rb