Nobody
2015/11/28 16:11:10 投稿
4

ブロックを使って、繰り返し使うコードをメソッドに切り出す

Before

# fbのfeedを全て取得する
def get_fb_feeds(fb_api_client)
  option = {iam: 'fb'}
  response = fb_api_client.get_feeds(option)
  fb_feeds = response

  until response.empty?
    option[:max_id] = response.last.id
    response = fb_api_client.get_feeds(option)
    fb_feeds += response
  end

  fb_feeds.flatten
end

# twのtweetを全て取得する
def get_tw_tweets(tw_api_client)
  option = {iam: 'tw'}
  response = tw_api_client.get_tweets(option)
  tw_tweets = response

  until response.empty?
    option[:from_id] = response.last.id
    response = tw_api_client.get_tweets(option)
    tw_tweets += response
  end

  tw_tweets.flatten
end

After

def paginate(&block)
  response = yield(nil)
  sns_posts = response

  until response.empty?
    response = yield(response)
    sns_posts += response
  end

  sns_posts.flatten
end

# fbのfeedを全て取得する
def get_fb_feeds(fb_api_client)
  option = {iam: 'fb'}
  paginate do |response|
    option[:max_id] = response.last.id unless response.nil?
    fb_api_client.get_feeds(option)
  end
end

# twのtweetを全て取得する
def get_tw_tweets(tw_api_client)
  option = {iam: 'tw'}
  paginate do |response|
    option[:from_id] = response.last.id unless response.nil?
    tw_api_client.get_tweets(option)
  end
end

みんなのコメント