【发布时间】:2017-03-07 00:28:43
【问题描述】:
我正在开发一个调用 Twitter 和 Spotify API 的应用程序。用户通过推特认证后,重定向到playlist.erb,即回调地址。
我的问题是 playlist.erb 页面需要一段时间才能呈现,因为首先我们必须调用以获取在用户 Twitter 页面上找到的所有推文,然后尝试查找有关歌曲/艺术家的信息,然后使用 Spotify API搜索与用户指定的信息最接近的歌曲。为每条推文执行此操作需要相当长的时间。对于 10 条推文,有时需要 5-10 秒。总共限制为 50 条推文。
当前playlist.erb页面完全加载后的looks like this。
我的问题是,有没有一种方法可以让我先渲染页面,然后让每个单独推文的部分内容一次渲染一个, 在每条推文加载时为其添加一个新行?
我读到我应该使用一种叫做 AJAX 的东西,但我不确定如何在这里实现它。
另外我知道我的观点可以使用 CSS 重构方面的修复,而不是使用已弃用的 <center></center> HTML 标签。而且我可能应该使用适当的 MVC 对系统进行整体重构。
在 playlist.erb 中,通过 TweetsController 调用 Twitter API 以查找页面中的所有推文。当new_tweet(tweet.text) 被调用时,_tweet.erb 部分被渲染到每个推文的这个视图。此方法调用 Spotify API 以查找有关推文中提到的歌曲的详细信息。
new_tweet 是一个名为 playlist_helper.rb 的助手中的方法。
load_tweets 是一个名为tweets_controller.rb 的控制器中的方法。
我意识到在视图中放入相当多的逻辑,这就是为什么页面需要很长时间才能加载的原因。
playlist.erb
<% loaded_tweets = TweetsController.load_tweets(current_user) %>
<% if loaded_tweets.any? %>
<table class='tweet_view'>
<thead>
<tr class='tweet_row'>
<th class="fixed_cover"><div class='tableheader'><h6 style='color:white'>Cover</h6></div></th>
<th class="fixed_spotify"><div class='tableheader'><h6 style='color:white'>Spotify</h6></div></th>
<th class="fixed_title"><div class='tableheader'><h6 style='color:white'>Track title</h6></div></th>
<th class="fixed_artist"><div class='tableheader'><h6 style='color:white'>Artist</h6></div></th>
<th class="fluid"><div class='tableheader'><h6 style='color:white'>Album</h6></div></th>
</tr>
</thead>
<tbody>
<% loaded_tweets.reverse_each.each do |tweet| %>
<%=new_tweet(tweet.text)%>
<% end %>
</tbody>
</table>
<% else %>
<center>
<p><h8><b>No tweets found!</b></h8></p>
</center>
<% end %>
_tweet.erb 部分只是为每首歌曲添加一个新行。
_tweet.erb
<tr class='tweet_row'>
<td class='tweet_column'>
<div class='tablerow#cover'>
<%= image_tag(@cover,:class => 'album_cover')%>
</div>
</td>
<td class='tweet_column'>
<div class='tablerow#spotify'>
<h5><%= link_to image_tag('spotify', :class => 'spotify_image'), 'https://open.spotify.com/track/'+@spotify %></h5>
</div>
</td>
<td class='tweet_column'>
<div class='tablerow'>
<h5><%=@track_name%></h5>
</div>
</td>
<td class='tweet_column'>
<div class='tablerow'>
<h5><%=@artist%></h5>
</div>
</td>
<td class='tweet_column'>
<div class='tablerow'>
<h5><%=@album%></h5>
</div>
</td>
</tr>
【问题讨论】:
标签: ruby-on-rails ruby model-view-controller render partials