我正在开发一个调用Twitter和Spotify API的应用程序。在用户通过twitter进行身份验证后,它们被重定向到playlist.erb,即回调url。
我的问题是,呈现playlist.erb页面需要一段时间,因为首先我们必须调用以获取在用户Twitter页面上找到的所有tweet,然后尝试查找有关歌曲/艺术家的信息,然后使用Spotify API搜索与用户指定的信息最接近的歌曲。为每条推文做这件事需要很长时间。在10条推特上,有时需要5-10秒。这个限制总共是50条微博。
在完全加载playlist.erb后的当前看起来像这样页面。
我的问题是,是否有一种方法可以先呈现页面,然后得到每个不可分割的tweet的部分,然后一次呈现一个,在加载时为每个tweet添加一个新行? 我已经读过应该使用AJAX的东西,但是我不知道如何在这里实现它。
我还知道,我的视图可以使用CSS重构而不是使用不推荐的<center></center>标记进行修复。我可能应该使用适当的MVC完成整个系统的重构。
在playlist.erb中,通过TweetsController调用Twitter来查找页面中的所有tweet。然后,当调用_tweet.erb时,将每个tweet的new_tweet(tweet.text)部分呈现到此视图。此方法调用Spotify API以查找tweet中提到的歌曲的详细信息。
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>发布于 2017-03-07 14:30:37
将playlist.html.erb playlist.erb更改为
<div id="tweets">
<%= render 'tweet') %>
</div>…………
<script>
$( document ).ready(function() {
// call the controller function here
});
</script>在控制器方法中添加
…………
respond_to do |format|
format.js
end在action_name.js.erb这样的视图文件夹中再创建一个文件并添加
$('#tweets').html('<%= j(render "tweet") %>')https://stackoverflow.com/questions/42638080
复制相似问题