自己完結

完全に雑記

2017/09/15

今日あった事

  • テストをしてました。

rails

前略、Twitterのファボ(死語)画像をもりっと出すアプリを作ろうと思った。 昨日まででとりあえず画像がもりっと出るようになったが、ページめくり的な事はできなかったのだった。

ということで超適当なpagerを作った

twitter_controller.rb

#!/usr/bin/ruby
# coding: utf-8

class TwitterController < ApplicationController
  def show
    Dotenv.load

    client = Twitter::REST::Client.new do |config|
      config.consumer_key = ENV['Consumer_Key']
      config.consumer_secret = ENV['Consumer_Secret']
      config.access_token = ENV['Access_Token']
      config.access_token_secret = ENV['Access_Secret']
    end

    count = 200
    is_blank = params[:max_id].blank? && params[:since_id].blank?
    is_next = !params[:max_id].blank?
    is_prev = !params[:since_id].blank?

    if is_blank
      fav_tweets = client.favorites(count: count)
    elsif is_next
      fav_tweets = client.favorites(count: count, max_id: params[:max_id])
    elsif is_prev
      fav_tweets = client.favorites(count: count, since_id: params[:since_id])
    end

    @result = []

    fav_tweets.each do |tweet|
      if !tweet.media.blank?
        tweet.media.each do |media|
          @result << media.media_url_https.to_s
        end
      elsif !tweet.urls.blank?
        tweet.urls.each do |url|
          @result << url.url.to_s
        end
      end
    end

    @first = fav_tweets.first.id
    @last = fav_tweets.last.id
  end
end
  • max_id を指定すると、そのIDを含まず次のツイートからカウント分ツイートを取得する
  • since_id を指定すると、そのIDを含まず前のツイートからカウント分ツイートを取得する

  • params[:hoge] get時のパラメタを取得するぞ!

で、Viewはこう show.html.erb

<% if @result %>
  <%= @result.each do |url| %>
    <%= link_to image_tag(url, {width:100, height: '25%'}), url %>
  <% end %>
<% end %>
<% if @first %>
  <%= link_to '前へ', controller: 'twitter', action: 'show', since_id: @first %>
<% end %>
<% if @last %>
  <%= link_to '次へ', controller: 'twitter', action: 'show', max_id: @last %>
<% end %>

とりあえず…… ページめくりは出来たぞ…… これが良いのか悪いのかもわからんが……。