0

Я пытаюсь загрузить результат поиска Youtube с помощью его API.
Она выглядит прекрасно работать, но до сих пор иногда получаю эту ошибкуПочему он иногда получает «неопределенный метод` videoId »?

ActionView::Template::Error (undefined method `videoId' for #<Google::APIClient::Schema::Youtube::V3::ResourceId:0x000000072afcb8>): 

Я просто интересно, если YouTube не будет предоставлять свою VideoID иногда под какой-то конкретной ситуации?

Как я могу избежать этой проблемы?

CONTROLLER

. 
. 
. 
@search_response = client.execute!(
    :api_method => youtube.search.list, 
    :parameters => { 
    :part => 'snippet', 
    :q => 'cat', 
    :maxResults => 10, 
    :order => 'date', 
    :pageToken => pageToken 
    } 
) 
. 
. 
. 

VIEW

<% @search_response.data.items.each do |video| %> 
    ID: <%= video.id.videoId %><br /> 
    Title: <%= video.snippet.title %><br /> 
    Description: <%= video.snippet.description %><br /> 
    <img src="<%= video.snippet.thumbnails.high.url %>" with="480" height="360"><br /> 
    <br /> 
    <br /> 
<% end %> 


<%= debug @search_response.data.items %> 

Вывод отладочных

- !ruby/object:Google::APIClient::Schema::Youtube::V3::SearchResult 
    data: 
    kind: youtube#searchResult 
    etag: ! '"Y3xTLFF3RLtHXX85JBgzzgp2Enw/RtuotxAng6F5sgkBlbg_LTSDi7s"' 
    id: 
     kind: youtube#video 
     videoId: d5TsLsjtth8 
    snippet: 
     publishedAt: '2015-06-29T04:19:43.000Z' 
     channelId: UCxdQj_S7w5O9lEm6v2uH_EA 
     title: ! '◕‿◕☞ Funny Cats Funny Cat Videos Funny Cat Vine Most Funny Cat 
     2016 #2' 
     description: funny vines clean version funny vines compilation 2015 new funny 
     vines christian delgrosso funny vines cartoon voice overs funny fails dirt 
     bike funny fails don't ... 
     thumbnails: 
     default: 
      url: https://i.ytimg.com/vi/d5TsLsjtth8/default.jpg 
     medium: 
      url: https://i.ytimg.com/vi/d5TsLsjtth8/mqdefault.jpg 
     high: 
      url: https://i.ytimg.com/vi/d5TsLsjtth8/hqdefault.jpg 
     channelTitle: '' 
     liveBroadcastContent: none 
- !ruby/object:Google::APIClient::Schema::Youtube::V3::SearchResult 
    data: 
    kind: youtube#searchResult 
    etag: ! '"Y3xTLFF3RLtHXX85JBgzzgp2Enw/wXXxhJIuGlDPCjNyD6fxNnnp9yA"' 
    id: 
     kind: youtube#video 
     videoId: 812W82_VDaA 
    snippet: 
     publishedAt: '2015-06-29T03:57:38.000Z' 
     channelId: UCH9ev60cc7IFU_fqhBEpChw 
     title: ! 'The Cat, the Vagabond and the Victim: A Cats in Trouble' 
     description: ! 'The Cat, the Vagabond and the Victim: A Cats in Trouble http://www.amazon.co.uk/dp/B00U259982?tag=weiradlaemm06-21 
     Feature * Heir of the cat... When ...' 
     thumbnails: 
     default: 
      url: https://i.ytimg.com/vi/812W82_VDaA/default.jpg 
     medium: 
      url: https://i.ytimg.com/vi/812W82_VDaA/mqdefault.jpg 
     high: 
      url: https://i.ytimg.com/vi/812W82_VDaA/hqdefault.jpg 
     channelTitle: '' 
     liveBroadcastContent: none 
- !ruby/object:Google::APIClient::Schema::Youtube::V3::SearchResult 
    data: 
    kind: youtube#searchResult 
    etag: ! '"Y3xTLFF3RLtHXX85JBgzzgp2Enw/QWxRfjhIEHs95Rw1BSFjPwamYVY"' 
    id: 
     kind: youtube#video 
     videoId: 4c2OvbRT1ZQ 
    snippet: 
     publishedAt: '2015-06-29T03:51:47.000Z' 
     channelId: UCvrbFkZE2CXP8SVK3w5XS4A 
     title: ネコのケンカ? - cat fight? - 
     description: 諦めなければいつかは叶うw. 
     thumbnails: 
     default: 
      url: https://i.ytimg.com/vi/4c2OvbRT1ZQ/default.jpg 
     medium: 
      url: https://i.ytimg.com/vi/4c2OvbRT1ZQ/mqdefault.jpg 
     high: 
      url: https://i.ytimg.com/vi/4c2OvbRT1ZQ/hqdefault.jpg 
     channelTitle: '' 
     liveBroadcastContent: none 
- !ruby/object:Google::APIClient::Schema::Youtube::V3::SearchResult 
    data: 
    kind: youtube#searchResult 
    etag: ! '"Y3xTLFF3RLtHXX85JBgzzgp2Enw/Ezf1iUMSd4dY_5GJ7Rb0MxDaJcI"' 
    id: 
     kind: youtube#video 
     videoId: -n040rD3nxI 
    snippet: 
     publishedAt: '2015-06-29T02:40:30.000Z' 
     channelId: UCsukgxUI8Gkju1lKCOKBlcQ 
     title: Funny Cat Joke 
     description: King of shitty 10 second videos. 
     thumbnails: 
     default: 
      url: https://i.ytimg.com/vi/-n040rD3nxI/default.jpg 
     medium: 
      url: https://i.ytimg.com/vi/-n040rD3nxI/mqdefault.jpg 
     high: 
      url: https://i.ytimg.com/vi/-n040rD3nxI/hqdefault.jpg 
     channelTitle: realchris1Returns 
     liveBroadcastContent: none 
- !ruby/object:Google::APIClient::Schema::Youtube::V3::SearchResult 
    data: 
    kind: youtube#searchResult 
    etag: ! '"Y3xTLFF3RLtHXX85JBgzzgp2Enw/TNpAkcwloC58Xi8aCVsmSXMspyA"' 
    id: 
     kind: youtube#video 
     videoId: e5LJvFUM9k4 
    snippet: 
     publishedAt: '2015-06-29T02:40:12.000Z' 
     channelId: UC64ta8zKaK5gXWPgTk37VNA 
     title: ! 'Sam & Cat Season 1 : FULL Episode 1 - 36 FREE STREAMING HD QUALITY' 
     description: ! 'Sam & Cat - Season 1 : Episode 1 - 36 FULL STREAMING , Visit 
     Link On List All Episode http://youtube.vg/HVDX3KE8 And Enjoyed For 720p Until 
     1280p High ...' 
     thumbnails: 
     default: 
      url: https://i.ytimg.com/vi/e5LJvFUM9k4/default.jpg 
     medium: 
      url: https://i.ytimg.com/vi/e5LJvFUM9k4/mqdefault.jpg 
     high: 
      url: https://i.ytimg.com/vi/e5LJvFUM9k4/hqdefault.jpg 
     channelTitle: '' 
     liveBroadcastContent: none 
- !ruby/object:Google::APIClient::Schema::Youtube::V3::SearchResult 
    data: 
    kind: youtube#searchResult 
    etag: ! '"Y3xTLFF3RLtHXX85JBgzzgp2Enw/HcqCoYiw3qvNoxloToHL_LeyAk4"' 
    id: 
     kind: youtube#video 
     videoId: x4RB5oF72AU 
    snippet: 
     publishedAt: '2015-06-29T02:07:49.000Z' 
     channelId: UCFPV7m24Y-KM66v_aScWTRQ 
     title: Kucing Berani serang Ular (cat vs snake) 
     description: Kucing Berani serang Ular (cat vs snake) 
     thumbnails: 
     default: 
      url: https://i.ytimg.com/vi/x4RB5oF72AU/default.jpg 
     medium: 
      url: https://i.ytimg.com/vi/x4RB5oF72AU/mqdefault.jpg 
     high: 
      url: https://i.ytimg.com/vi/x4RB5oF72AU/hqdefault.jpg 
     channelTitle: '' 
     liveBroadcastContent: none 
- !ruby/object:Google::APIClient::Schema::Youtube::V3::SearchResult 
    data: 
    kind: youtube#searchResult 
    etag: ! '"Y3xTLFF3RLtHXX85JBgzzgp2Enw/dTOXDCV4PSk4woUH3RTDfYWH7sc"' 
    id: 
     kind: youtube#video 
     videoId: cfuq0Qs4154 
    snippet: 
     publishedAt: '2015-06-29T02:05:19.000Z' 
     channelId: UCH1vIUNu9z4hosPO4IiEDKg 
     title: MY CUTE CAT VIDEO XD 
     description: I MADE THIS VIDEO FOR FUN BECAUSE IT WOULD BE A CUTE FUN IDEAXD. 
     thumbnails: 
     default: 
      url: https://i.ytimg.com/vi/cfuq0Qs4154/default.jpg 
     medium: 
      url: https://i.ytimg.com/vi/cfuq0Qs4154/mqdefault.jpg 
     high: 
      url: https://i.ytimg.com/vi/cfuq0Qs4154/hqdefault.jpg 
     channelTitle: Nlg31 
     liveBroadcastContent: none 
- !ruby/object:Google::APIClient::Schema::Youtube::V3::SearchResult 
    data: 
    kind: youtube#searchResult 
    etag: ! '"Y3xTLFF3RLtHXX85JBgzzgp2Enw/3VF2zQBJ71Si2Zcar34cJGKDp6A"' 
    id: 
     kind: youtube#playlist 
     playlistId: PLMPGTLYCAiq9gAh6UnpaXx_PtKENmh1P6 
    snippet: 
     publishedAt: '2015-06-29T01:52:34.000Z' 
     channelId: UCl65ZDJ_D2QnvzknOzC_Syw 
     title: Black Cat 
     description: '' 
     thumbnails: 
     default: 
      url: https://i.ytimg.com/vi/UexNlx4mj1g/default.jpg 
     medium: 
      url: https://i.ytimg.com/vi/UexNlx4mj1g/mqdefault.jpg 
     high: 
      url: https://i.ytimg.com/vi/UexNlx4mj1g/hqdefault.jpg 
     channelTitle: '' 
     liveBroadcastContent: none 
- !ruby/object:Google::APIClient::Schema::Youtube::V3::SearchResult 
    data: 
    kind: youtube#searchResult 
    etag: ! '"Y3xTLFF3RLtHXX85JBgzzgp2Enw/nldPN_K-A-jNCqF0I3MlOjByOog"' 
    id: 
     kind: youtube#video 
     videoId: INraypSN3Q0 
    snippet: 
     publishedAt: '2015-06-29T01:35:33.000Z' 
     channelId: UCVbqIMbp2qRhK6-YXYkOF7g 
     title: ! 'Aksi kucing dubsmash lucu.. #funny #cat #pet' 
     description: Hilarious cats. 
     thumbnails: 
     default: 
      url: https://i.ytimg.com/vi/INraypSN3Q0/default.jpg 
     medium: 
      url: https://i.ytimg.com/vi/INraypSN3Q0/mqdefault.jpg 
     high: 
      url: https://i.ytimg.com/vi/INraypSN3Q0/hqdefault.jpg 
     channelTitle: '' 
     liveBroadcastContent: none 
- !ruby/object:Google::APIClient::Schema::Youtube::V3::SearchResult 
    data: 
    kind: youtube#searchResult 
    etag: ! '"Y3xTLFF3RLtHXX85JBgzzgp2Enw/2_PMO7FctA_79aqVhV0D83Yw7VY"' 
    id: 
     kind: youtube#video 
     videoId: Bt6NgC0peLI 
    snippet: 
     publishedAt: '2015-06-29T01:06:00.000Z' 
     channelId: UCpM_hmOVus872lSLIdbirXQ 
     title: ! 'Conversation With a Cat: Should I Go Vegan?' 
     description: I'm 80% vegan, but my cat won't hesitate to eat lizards/birds... 
     thumbnails: 
     default: 
      url: https://i.ytimg.com/vi/Bt6NgC0peLI/default.jpg 
     medium: 
      url: https://i.ytimg.com/vi/Bt6NgC0peLI/mqdefault.jpg 
     high: 
      url: https://i.ytimg.com/vi/Bt6NgC0peLI/hqdefault.jpg 
     channelTitle: LifeLibertyNow 
     liveBroadcastContent: none 

ответ

1

Это может быть просто becaus e результат поиска не возвращает видео.

Результаты поиска: kind Возможно, он был youtube#playlist или youtube#channel, а не youtube#video. В таких случаях вы можете проверить на playlistId или channelId.

1

Один из способов четко определить, что происходит не так здесь является Law of Demeter:

  • Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.
  • Each unit should only talk to its friends; don't talk to strangers.
  • Only talk to your immediate friends.

Что вам не нужно рабски подчиняться, но часто может сказать вам, когда что-то не так с системой.

Так что, когда вы делаете video.snippet.thumbnails.high.url, вы не просто нарушаете Закон Деметры - вы много раз управляете им - с грузовиком.

Так позволяет переписать:

@search_response = client.execute!(
    :api_method => youtube.search.list, 
    :parameters => { 
    :part => 'snippet', 
    :q => 'cat', 
    :maxResults => 10, 
    :order => 'date', 
    :pageToken => pageToken 
    } 
) 

data = @search_response.data 
@videos = @search_response.data.try(:items) || [] 

По вашему мнению

<% @videos.each do |video| %> 
    <%- snippet = video.snippet -%> 
    <%- if video.id -%> 
    ID: <%= video.id.try(:videoId) %><br /> 
    <%- end -> 
    <%- if snippet -%> 
    Title: <%= snippet.title %><br /> 
    Description: <%= snippet.description %><br /> 
    <%- end -%> 
    <% 
    thumbnails = snippet.thumbnails 
    if thumbnails %> 
    <img src="<%= thumbnails.high.url %>" with="480" height="360">  
    <% end %> 
    <br /> 
    <br /> 
    <br /> 
<% end %> 

Однако, чтобы избежать такой бардак вы часто хотите нормализовать ответы, которые Вы получаете от API:

class Video 
    include ActiveModel::Model 
    attr_accessor :id 
    attr_accessor :thumbnails 
    attr_accessor :snippet 
    attr_accessor :description 
    attr_accessor :title 

    def initialize(hash = {}) 
    @id = hash.try[:id].try(:videoId), 
    @snippet = hash.try(:snippet), 
    @thumbnails = hash.try(:snippet).try(:thumbnails), 
    @description = hash.try(:snippet).try(:description) 
    @title = hash.try(:snippet).try(:title) 
    end 
end 

Значит, вы бы сделали

@videos = @videos.map { |v| Video.new(v) } 

И переписать вид:

<% @videos.each do |video| %> 
    ID: <%= video.id %><br /> 
    Title: <%= video.title %><br /> 
    Description: <%= video.description %><br /> 
    <% thumbnail = video.thumbnails.try(:high).try(:url) %> 
    <% if thumbnail %> 
    <img src="<%= thumbnail %>" with="480" height="360"><br /> 
    <% end %> 
    <br /> 
    <br /> 
<% end %> 
+0

Спасибо Я попробовал ваш ответ, но он по-прежнему дает ту же ошибку :(Это так странно, потому что на самом деле имеет VideoID, если я позволю это выводить отладочную так же, как выше (Я добавил дополнительную информацию в свой вопрос. пожалуйста, проверьте) – HUSTEN

+0

Имеет ли это значение, потому что videoId имеет капитализированный характер в нем? – HUSTEN

+0

'<% = video.id.try (: videoId)' возвращает 'undefined method 'videoId' ' – HUSTEN

Смежные вопросы