🕺
【Rails】YouTube APIを使用しチャンネルアイコンを取得
YouTube Data APIを使用して、チャンネルアイコンを取得し、アイコンをクリックしてyoutubeに飛べるようにする。
前提
YouTube APIの登録、設定は以下を参照ください。
アイコンを取得するために、俺の場合は、以下のようにchannel
というカラムを追加した。
class AddChannelToUsers < ActiveRecord::Migration[6.1]
def change
add_column :users, :channel, :string
end
end
channel
に自身のyoutubeチャンネルのリンクを入れることで、リンクからアイコンを抽出できるようにする。
APIキーの取得と設定
今回も2つのヘルパーを使用して実装する。それぞれの目的は以下の通り。
-
application_helper
与えられたYouTubeのURLからチャンネルIDを抽出するためのヘルパーメソッド。YouTubeのURLがチャンネルページかユーザーページかを認識し、それに基づいてチャンネルIDを取得する。 -
channel_icon_helper
チャンネルIDを使用して、YouTubeチャンネルのアイコン画像を取得するためのヘルパーメソッド。
application_helperの設定
app/helpers/application_helper.rb
module ApplicationHelper
def extract_youtube_channel_id(url)
# YouTubeチャンネルURLの正規表現パターンにマッチするか確認
if url =~ %r{https?://(?:www\.)?youtube\.com/channel/([^/]+)}
$1 # マッチした部分(チャンネルID)を返す
elsif url =~ %r{https?://(?:www\.)?youtube\.com/user/([^/]+)}
# ユーザーページの場合、ページのHTMLコードを取得してチャンネルIDを抽出
response = Net::HTTP.get(URI.parse(url))
if match = response.match(%r{"externalChannelId":"([^"]+)"})
match[1] # マッチした部分(チャンネルID)を返す
end
end
end
end
上述を設定することで、YouTubeチャンネルURLからチャンネルIDを抽出する。
channel_icon_helperの設定
以下のファイルを新規作成し、記述する。
app/helpers/channel_icon_helper.rb
module ChannelIconHelper
def youtube_channel_icon(channel_id, options = {})
require 'google/apis/youtube_v3'
# オプションをデフォルト値とマージ
options = { size: 'default', alt: 'Channel Icon' }.merge(options)
# YouTube APIを使用してチャンネルの情報を取得
service = Google::Apis::YoutubeV3::YouTubeService.new
service.key = ENV['YOUTUBE_API_KEY']
channel_response = service.list_channels('snippet', id: channel_id)
channel_item = channel_response.items.first
# サイズに応じてチャンネルのアイコンURLを取得
channel_icon_url = case options[:size]
when 'default'
channel_item.snippet.thumbnails.default.url
when 'medium'
channel_item.snippet.thumbnails.medium.url
when 'high'
channel_item.snippet.thumbnails.high.url
else
channel_item.snippet.thumbnails.default.url
end
# アイコンの画像タグを生成して返す
image_tag(channel_icon_url, options)
end
end
APIキーは環境変数に入れ、情報漏洩しないよう注意すること
ビューでの呼び出し
ヘルパーを呼び出す記載をしていく。
- youtubeのチャンネルリンクをつける場合
<% channel_id = extract_youtube_channel_id(@user.channel) %>
<%= link_to youtube_channel_icon(channel_id, size: 'default', class: 'channel-icon rounded-circle'), "https://www.youtube.com/channel/#{channel_id}", target: "_blank" %>
default
は一番小さいサイズ。
bootstrapを入れているので、アイコンを丸くするclassを入れている。
アイコンをクリックするとyoutubeチャンネルページへ飛ぶ。
- チャンネルリンクをつけない場合
<% channel_id = extract_youtube_channel_id(@user.channel) %>
<%= youtube_channel_icon(channel_id, size: '40x40', class: 'channel-icon rounded-circle') %>
上述のようにsize
の指定も可能。
Discussion