padrino でのウェブサービス作りを実況してみる

padrino でのウェブサービス作りを実況してみる

概要

twitter で書きなぐったのをまとめてブログとかwikiとかshortnote にあげる

まずはプロジェクトとか

プロジェクト名は、"timeline_editor"。安易ですね。

% pwd
/home/source
% padrino g project timeline_editor -d activerecord -e erb -s jquery -t rspec
....
% cd timeline_editor
% vi app/app.rb
module TimelineEditor
  class App < Padrino::Application
    ...
    get :index, map: "/" do
      erb "hello world"
    end
  end

レイアウト

bootstrap 使って見てくれを整えます。

% vi app/views/layouts/application.erb
<html>
<head>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <script type="text/javascript" src="http://getbootstrap.com/dist/js/bootstrap.min.js"></script>
  <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
  <div class="navbar navbar-default">
    <ul class="nav navbar-nav">
      <li><a href="/">top</a></li>
    </ul>
  </div>
  <div class="container">
    <div class="panel panel-primary">
      <div class="panel-heading">title</div>
      <div class="panel-body"><%= yield %></div>
    </div>
    <div class="panel panel-primary">
      <div class="panel-heading">ENV</div>
      <div class="panel-body">
    <div><h2>env</h2><%= h env.inspect %></div>
      </div>
    </div>
  </div>
</body>
</html>

bootstrap は後ほど取り上げるけど、ソレっぽく見てくれを整えてくれる。 ナビゲーションバーを上に、中身を "panel" で包むと見やすい。

timeline を表示させる

gem の twitter を使おう。consumer key/secret は取っておいてね。

% vi Gemfile
...
gem 'twitter'
% bundle
...
% vi app/app.rb
    get :user_timeline do
      twitter = Twitter::REST::Client.new do |config|
        config.consumer_key = "xxx"
        config.consumer_secret = "xxx"
        config.access_token = "xxx"
        config.access_token_secret = "xxx"
      end 
      timeline = twitter.user_timeline(count: 50)
      erb timeline.map {|status| status.text }.inspect
    end

key や token の類はとりあえず決め打ちにします。config化や認証は後で。 inspect して status が取れてるか確認。 そしたら view を使ってみる。

% vi app/app.rb
    get :user_timeline do
      ...
      timeline = twitter.user_timeline(count: 50)
      erb partial 'status', :collection => timeline
...
% vi app/views/_status.erb
<li><%= h status.text %></li>

partial template を使います。対象オブジェクトの配列をcollection で渡して view で "_" から始まるテンプレートファイルを作って partial を呼ぶと、配列回してくれるらしいです。便利ですね。