前回の続きです。
前回は2ch.scのスレッドをスクレイピングして取得して表示する所までやりました。
今回は1つの板のスレッド一覧を取得して表示し、その板全体のスレッドをそれぞれ表示させられるようにしたいと思います!:D
環境
以前と同じです。
macOS Sierra 10.12.6
Visual Studio Code 1.16.0
Ruby on Rails 5.0.6
Ruby 2.3.1
rbenv 1.1.1-2-g615f844
MySQL 5.7.17
板のコントローラ・ビューを作成
$ rails g controller subbacks index
http://localhost:3000/subbacks/index
に接続してみると、ビューファイルが作成されていることが確認できる。
ルーティングを編集
Rails.application.routes.draw do
get 'subbacks/:subback_id' => 'subbacks#index'
get 'threads/:subback_id/:thread_id' => 'threads#index'
end
subbacks/params[:subback_id]
で任意の板のスレッド一覧を、
threads/:subback_id/:thread_id
で任意の板の任意のスレッドを表示します。
板のコントローラを編集
class SubbacksController < ApplicationController
def index
agent = Mechanize.new
url = get_url
page = agent.get(url)
html = Nokogiri::HTML(page.body)
@subback_title = html.css('head title').text.sub('@2ch掲示板#スレッド一覧', '');
@threads = []
is_removed_guide = false
html.css('small#trad a').each do |thread_title|
if thread_title.attribute('class').try(:value) == 'sc' && !is_removed_guide
is_removed_guide = true
next
end
thread_title['href'] = thread_title.attribute('href').try(:value).sub(/l50/, '').insert(0, '/threads/anime2/')
title = thread_title.to_html.sub(/\d{1,3}: ?/, '')
thread = {title: title}
@threads << thread
end
end
def get_url
url = 'http://ikura.2ch.sc/' + params[:subback_id] + '/subback.html'
end
end
Mechanizeでスレッド一覧を取得して、板名から@2ch掲示板#スレッド一覧
を取り除いた文字列を@subback_titleに代入し、配列@threadsには取得したスレッドタイトルをhtml形式(リンク付き)で格納します。
また、スレッド番号(1: など)は削除しています。
スレッドリンクは、末尾の/l50
を取り除いて、スレッド全体を開けるようにしました。
スレッドのパーシャルを作成
.thread
.thread-title
= simple_format(thread[:title])
板のビューを編集
.subback-header
%span
= @subback_title
.thread-box
- @threads.each do |thread|
= render 'thread', thread: thread
板のcssを整える
.subback-header {
height: 2rem;
background-color: #777;
color: #FFF;
text-align: center;
line-height: 35px;
font-weight: bold;
a {
font-size: 17px;
}
}
.thread-box {
margin: 10px 30px 0;
padding-bottom: 20px;
a {
color: #FFF;
text-decoration: none;
&:hover{
color: #CCC;
}
}
}
@media screen and (max-width:1024px){
.subback-header {
font-size: 13px;
}
.thread-box {
font-size: 12px;
margin: 0 3px;
padding-bottom: 0;
}
}
ここまでで特定の板からスレッド一覧を取得するところと、その板のスレッドを開くところまでは完成です!:D
次回は板一覧を取得してトップページに表示させようと思います。