Padrinoを触ってみた

Padrino で素敵なウェブ開発を - Padrino Ruby Web Framework
Padrinoってのがあるみたい


チュートリアルを参考にしながら、作ってみました。

Guides Basic Projects - Padrino Ruby Web Framework
このページを参考にしました

インストール
gem install padrino
プロジェクトの作成
padrino g project test_app -d datamapper -e haml
  • -d ORMの選択
  • -e テンプレートエンジンの選択

作業ポイント

herokuへのデブロイ準備

以下のコマンドを叩けば、

をやってくれるみたい!

padrino gen plugin heroku
hamlで日本語を使うには、エンコードの指定が必要
-# coding: utf-8
rakeコマンド

いままで、頑張って、サンプル通り、heroku rake ar:auto:migrate ってやってたけど、
ar ってActiveRecordの略か・・・
Datamapper使うなら、dmだったよ

heroku rake -T

ってやれば、タスク一覧を取得できることを把握。


次やりたいこと

  • jQueryを使えるようになりたい

TEDから取得したmp3に英語原稿を埋め込む

TEDの英語原稿を取得する - ギークを夢見るじょーぶん男子で取得した英語原稿をダウンロードしたmp3ファイルに埋め込みたい!!


調べてみると、id3lib-rubyが使えそう。

id3lib-rubyを利用してmp3に歌詞情報を埋め込む

id3lib-ruby - ID3 tag library for Ruby
mp3のタグを扱うライブラリid3libのラッパー


準備
brew install id3lib
gem install id3lib-ruby
Lyricsに英語原稿を設定
require 'rubygems'
require 'id3lib'

# TEDからダウンロードしたmp3ファイルの読み込み
tag = ID3Lib::Tag.new('ted.mp3')
# 英語原稿を歌詞情報として登録
tag.lyrics = "TEDから取得した英語原稿"
# 更新
tag.update!

できた!


課題
  • 日本語を埋め込もうと思うとうまくいかない。文字コードの問題を解決できなかった。

TEDの英語原稿を取得する

方針

http://www.ted.com/talks/subtitles/id/#{固有のID}/lang/en を叩くと、英語原稿のjsonが返ってくる。
TEDのビデオの固有のIDを取得して、API叩いて、jsonをparseして、出力すればいけそう。

jsonのパース
gem install json
require 'rubygems'
require 'open-uri'
require 'json'

open("http://www.ted.com/talks/subtitles/id/1183/lang/en") do |f|
  json = JSON.parse(f.read)
  json['captions'].each do |j|
    puts j['content']
  end
end


こんな感じで取得できそう。


固有IDを取得するために、nokogiriでHTMLをparseする

Nokogiri
Installationを参照して nokorigiのgemを入れる


brew update
brew install libxml2 libxslt
gem install nokogiri
require 'rubygems'
require 'open-uri'
require 'json'
require 'nokogiri'

url = "http://www.ted.com/talks/brene_brown_listening_to_shame.html"
doc = Nokogiri::HTML(open(url))

ted_id = doc.xpath("//div[@id='share_and_save']").first.attribute("data-id")

open("http://www.ted.com/talks/subtitles/id/#{ted_id}/lang/en") do |f|
  json = JSON.parse(f.read)
  json['captions'].each do |j|
    puts j['content']
  end
end


スクレイピングの方法がわからなくて四苦八苦。以下を参照して、怪しげながら、固有IDの取得。
document/ruby nokogiri スクレイピング - weiki (作業ログやそのまとめ)
XPath入門、実用例 - 素人がプログラミングを勉強するブログ


できた

TED


multi-termでterm内にコピー&ペーストできるようにする

Emacs 上で快適に Bash や Zsh を利用する設定 : 紹介マニア
デフォルトでは multi-term には対応していませんが以下のように設定すると対応できます。以下の設定では F8 を押すと、 multi-term で起動した shell がフレームを分割して起動 ...
いつも参考にさせてもらってます


;; multi-term
(when (require 'multi-term nil t)
  (setq multi-term-program "/bin/zsh")
  (add-hook 'term-mode-hook
         '(lambda ()
            ;; C-h を term 内文字削除にする
            (define-key term-raw-map (kbd "C-h") 'term-send-backspace)
            ;; C-y を term 内ペーストにする
            (define-key term-raw-map (kbd "C-y") 'term-paste)
            )))


これでc-y でterm内にコピー&ペーストできるようになった。



LionにCocoaEmacsをソースコードからビルドしてインストール


本書読んで、改めてEmacsの設定を見なおそうと思ったので、そのときのメモ。
心機一転しようと、CocoaEmacsのインストールから始めました。

ソースコードからビルド

Xcodeがインストールされていることが前提。
一回、自分でビルドしてみたかったから、

curl -O http://ftp.gnu.org/pub/gnu/emacs/emacs-23.4.tar.gz
tar xvfz emacs-23.4.tar.gz
cd emacs-23.4
./configure --with-ns
make install


本書に書かれていたとおりにやってみると、タイトルバーがなくなってしまうという現象が・・・
調べてみると、フルスクリーンモードに対応するパッチを当てないといけないみたいです。

Emacs23.4をソースからインストール - 日々の設定
参考にさせてもらいましたー

さっき展開したEmacsのフォルダに移って、パッチを適用し、再度make install
cd emacs-23.4 
patch -p1 < ../emacs-23-lion-fullscreen-test.patch 
patch -p0 < ../inline_patch-23.1.92-b1/emacs-inline.patch
./configure --with-ns --without-x
make install


すると、nextstepEmacs.appができているので、アプリケーションフォルダに移せばインストール完了♪
CocoaEmacsになりました。

RackとRackで実現できること。

Sinatraとか、Sinatraで実装されているLokkaとか触ってるときに、そもそもRackってなんだ?って思って調べました。
前回のSinatra触ってると出てくるRackって何? - ギークを夢見るじょーぶん男子の続きです。

RackとRackで実現できること

.rb勉強会資料 - はじめる! Ruby de Web 開発
Rackとは?Rackで実現できることがスライドにまとまっていてわかりやすかった


これだけで、BASIC認証ができる!

use Rack::Auth::Basic do |user, pass|
  user == ENV['BASIC_USER'] && pass == ENV['BASIC_PASS']
end


Route 477 - Rack日本語リファレンス
Rackリファレンス

Route 477 - 5分でわかるRack , シュレーディンガーの猫たち

RubyからEvernoteAPIを使う-Web Application編-

前回のエントリ(RubyからEvernoteAPIを使ってノートブックの取得と、ノートの作成をする - ギークを夢見るじょーぶん男子)で、クライアントからAPIを使ってノートブックの取得と、ノートの作成はできました。

今回、Web Applicationとして、OAuthを使って認証して、EvernoteAPIを叩こうと思います。

APIキーの取得

APIキーのリクエスト

同じようにAPIキーを取得。
今回は、「Application Type」を「Web Application」を選択します。

サンプルを修正

以下のリンクからRubyのサンプルを取得。oauthフォルダに入ってるものが、Web Applicationのサンプルみたいです。Web ApplicationのRuby版のサンプルは、sinatraを使ったものでした。
http://evernote.s3.amazonaws.com/api/evernote-api-1.20.zip



自分の取得したAPIキーを反映するために、evernote_config.rbを 修正

require 'oauth'
require 'oauth/consumer'
require 'thrift'

# 以下、取得したAPIキー
OAUTH_CONSUMER_KEY = "YOUR_CONSUMER_KEY"
OAUTH_CONSUMER_SECRET = "YOUR_CONSUMER_SECRET"

# 定数
EVERNOTE_SERVER = "https://sandbox.evernote.com"
REQUEST_TOKEN_URL = "#{EVERNOTE_SERVER}/oauth"
ACCESS_TOKEN_URL = "#{EVERNOTE_SERVER}/oauth"
AUTHORIZATION_URL = "#{EVERNOTE_SERVER}/OAuth.action"
NOTESTORE_URL_BASE = "#{EVERNOTE_SERVER}/edam/note/"


Evetenoのgemを使うように、ちょこちょこ修正。

require "./evernote_config.rb"

としないと、読み込まれなかったのはなーぜー?

require 'rubygems'
require 'sinatra'
require 'evernote'
enable :sessions

# Load our dependencies and configuration settings
require "./evernote_config.rb"

##
# Verify that you have obtained an Evernote API key
##
before do
  if (OAUTH_CONSUMER_KEY == "en-edamtest") 
    halt '<span style="color:red">Before using this sample code you must edit evernote_config.rb and replace OAUTH_CONSUMER_KEY and OAUTH_CONSUMER_SECRET with the values that you received from Evernote. If you do not have an API key, you can request one from <a href="http://www.evernote.com/about/developer/api/">http://www.evernote.com/about/developer/api/</a>.</span>'
  end
end

##
# Index page
##
get '/' do
  erb :authorize
end

##
# Reset the session
##
get '/reset' do
  session[:request_token] = nil
  erb :authorize
end

##
# Get temporary credentials and redirect the user to Evernote for authoriation
##
get '/authorize' do
  callback_url = request.url.chomp("authorize").concat("callback")

  begin
    consumer = OAuth::Consumer.new(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET,{
        :site => EVERNOTE_SERVER,
        :request_token_path => "/oauth",
        :access_token_path => "/oauth",
        :authorize_path => "/OAuth.action"})
    session[:request_token] = consumer.get_request_token(:oauth_callback => callback_url)
    redirect session[:request_token].authorize_url

  rescue Exception => e
    @last_error = "Error obtaining temporary credentials: #{e.message}"
    erb :error
  end
end

##
# Receive callback from the Evernote authorization page and exchange the
# temporary credentials for an token credentials.
##
get '/callback' do
  if (params['oauth_verifier'].nil?)
    @last_error = "Content owner did not authorize the temporary credentials"
    erb :error
  else
    oauth_verifier = params['oauth_verifier']

    begin
      access_token = session[:request_token].get_access_token(:oauth_verifier => oauth_verifier)
      shard_id = access_token.params['edam_shard']

      # Construct the URL used to access the user's account
      noteStoreUrl = NOTESTORE_URL_BASE + shard_id
      noteStoreTransport = Thrift::HTTPClientTransport.new(noteStoreUrl)
      noteStoreProtocol = Thrift::BinaryProtocol.new(noteStoreTransport)
      noteStore = Evernote::EDAM::NoteStore::NoteStore::Client.new(noteStoreProtocol)

      # Build an array of notebook names from the array of Notebook objects
      notebooks = noteStore.listNotebooks(access_token.token)

      result = Array.new
      notebooks.each do |notebook| 
        result << notebook
      end
      @notebooks = result
      erb :complete
    rescue Exception => e
      @last_error = e
      erb :error
    end
   end
end


__END__


@@ layout
<html>
  <head>
    <title>Evernote Ruby OAuth Demo</title>
  </head>
  <body>
    <h1>Evernote Ruby OAuth Demo</h1>

    <p>
      This application uses the <a href="http://www.sinatrarb.com/">Sinatra framework</a> to demonstrate the use of OAuth to authenticate to the Evernote web service. OAuth support is implemented using the <a href="https://github.com/oauth/oauth-ruby">Ruby OAuth RubyGem</a>.
    </p>

    <p>
      On this page, we demonstrate how OAuth authentication might work in the real world.
      To see a step-by-step demonstration of how OAuth works, see <code>evernote_oauth.rb</code>.
    </p>

    <hr/>

    <h2>Evernote Authentication</h2>

    <%= yield %>

    <hr/>
    
    <p>
      <a href="/reset">Click here</a> to start over
    </p>

  </body>
</html>


@@ error
    <p>
      <span style="color:red">An error occurred: <%= @last_error.message %></span>
    </p>

@@ authorize
    <p>
      <a href="/authorize">Click here</a> to authorize this application to access your Evernote account. You will be directed to evernote.com to authorize access, then returned to this application after authorization is complete.
    </p>


@@ complete
    <p style="color:green">
      Congratulations, you have successfully authorized this application to access your Evernote account!
    </p>

    <p>
      You account contains the following notebooks:
    </p>

    <ul>
<% @notebooks.each do |notebook| %>
      <li><%= notebook.name %></li>
<% end %>
    </ul>
ターミナルから起動
ruby -rubygems evernote_oauth_simple.rb


http://localhost:4567で確認。動いた動いた。



次やりたいこと

  • herokuで動かしてみる。