2012年4月27日金曜日

MD5の作成

picasaにあるようなプライベート設定の認証キーにMD5を使う場合、
RubyからMD5キーを生成してみました。

irbで実行するとこんな感じ。
> require 'digest/md5'
=> true
> Digest::MD5.hexdigest("aa")
=> "4124bc0a9335c27f086f24ba207a4912"
> Digest::MD5.hexdigest("AA")
=> "3b98e2dffc6cb06a89dcb0d5c60a0206"

大文字小文字で違うキーが生成されます。

MD5のreverse用の辞書も存在するので、そこでマッチしない言葉を選びましょう!
http://md5.rednoize.com/

2012年4月20日金曜日

Sinatraをapacheで動かす

sinatraをapacheで動かしてみましょう。
Apacheが入ってることが前提で、passenger のインストールを行います。
先に作成した config.ru が必要になります。

下記を参考にしました!ありがとうございます!
http://d.hatena.ne.jp/foosin/20090619/1245426335

passengerのインストール
2つのモジュールが必要です。
1つ目はあっという間。
$ gem install passenger
Fetching: fastthread-1.0.7.gem (100%)
Building native extensions.  This could take a while...
Fetching: daemon_controller-1.0.0.gem (100%)
Fetching: passenger-3.0.12.gem (100%)
Successfully installed fastthread-1.0.7
Successfully installed daemon_controller-1.0.0
Successfully installed passenger-3.0.12
3 gems installed
Installing ri documentation for fastthread-1.0.7...
Installing ri documentation for daemon_controller-1.0.0...
Installing ri documentation for passenger-3.0.12...
Installing RDoc documentation for fastthread-1.0.7...
Installing RDoc documentation for daemon_controller-1.0.0...
Installing RDoc documentation for passenger-3.0.12...

2つ目はちょっと長いです。
$ passenger-install-apache2-module
Welcome to the Phusion Passenger Apache 2 module installer, v3.0.12.

This installer will guide you through the entire installation process. It
shouldn't take more than 3 minutes in total.

Here's what you can expect from the installation process:

 1. The Apache 2 module will be installed for you.
 2. You'll learn how to configure Apache.
 3. You'll learn how to deploy a Ruby on Rails application.

Don't worry if anything goes wrong. This installer will advise you on how to
solve any problems.

Press Enter to continue, or Ctrl-C to abort.
ここではとりあえずEnter押下。
しばし待つと
 1. The Apache 2 module will be installed for you.
が終わって、
 2. You'll learn how to configure Apache.

の説明が表示されます。

下記3行は環境によって異なりますので、メモしておきます。
あとで必要になります。
Load xxxxx
PassengerRoot xxxxx
PassengerRuby xxxxx

--------------------------------------------
The Apache 2 module was successfully installed.

Please edit your Apache configuration file, and add these lines:

   LoadModule passenger_module /home/tiffany/.rvm/gems/ruby-1.9.2-p290@rails3/gems/passenger-3.0.12/ext/apache2/mod_passenger.so
   PassengerRoot /home/tiffany/.rvm/gems/ruby-1.9.2-p290@rails3/gems/passenger-3.0.12
   PassengerRuby /home/tiffany/.rvm/wrappers/ruby-1.9.2-p290@rails3/ruby

After you restart Apache, you are ready to deploy any number of Ruby on Rails
applications on Apache, without any further Ruby on Rails-specific
configuration!

Press ENTER to continue.
無事インストールされたようなのでEnter押下。
最後に
 3. You'll learn how to deploy a Ruby on Rails application.

で、こういうメッセージが表示されます。
--------------------------------------------
Deploying a Ruby on Rails application: an example

Suppose you have a Rails application in /somewhere. Add a virtual host to your
Apache configuration file and set its DocumentRoot to /somewhere/public:

   <VirtualHost *:80>
      ServerName www.yourhost.com
      # !!! Be sure to point DocumentRoot to 'public'!
      DocumentRoot /somewhere/public   
      <Directory /somewhere/public>
         # This relaxes Apache security settings.
         AllowOverride all
         # MultiViews must be turned off.
         Options -MultiViews
      </Directory>
   </VirtualHost>

And that's it! You may also want to check the Users Guide for security and
optimization tips, troubleshooting and other useful information:

  /home/tiffany/.rvm/gems/ruby-1.9.2-p290@rails3/gems/passenger-3.0.12/doc/Users guide Apache.html

Enjoy Phusion Passenger, a product of Phusion (www.phusion.nl) :-)
http://www.modrails.com/

Phusion Passenger is a trademark of Hongli Lai & Ninh Bui.


Passengerのインストールはこれで終了です。


apacheの設定
環境によって異なると思いますが、、下記のファイルに上記3を参考に設定を行います。
$ sudo vi /etc/apache2/sites-available/xxx
そのファイルに下記を追加します。
上記でメモした3行

   LoadModule passenger_module /home/tiffany/.rvm/gems/ruby-1.9.2-p290@rails3/gems/passenger-3.0.12/ext/apache2/mod_passenger.so
   PassengerRoot /home/tiffany/.rvm/gems/ruby-1.9.2-p290@rails3/gems/passenger-3.0.12
   PassengerRuby /home/tiffany/.rvm/wrappers/ruby-1.9.2-p290@rails3/ruby
モジュールのパス設定
<VirtualHost *:80>
    ServerName www.yourhost.com
    DocumentRoot /home/tiffany/sinatra/public
    <Directory  /home/tiffany/sinatra/public>
        AllowOverride all
        Options -MultiViews
    </Directory>

     ErrorLog /var/log/apache2/error.log
     CustomLog /var/log/apache2/access.log combined
</VirtualHost>

これで、apacheを再起動すればOK!
RACK_ENV=productionでアプリが起動します。
もし、development環境でapache を動かしたい場合は、下記のようにRackEnv development をapacheの設定ファイルに追加してください。
    DocumentRoot /home/tiffany/sinatra/public
    RackEnv development

Sinatraをconfig.ruで起動

config.ruに下記を書くだけで動きます。

例えば、myqpp.rb のアプリを動かしたい場合
config.ru を myapp.rb と同じ階層に配置します。

#  config.ru
require "./myapp.rb"
run Sinatra::Application

require "./myapp.rb"
の記載は、下記のように書いてもOK
require File.dirname( __FILE__ ) + "/myapp.rb"

起動コマンドは
$ rackup config.ru
[2012-04-20 15:51:07] INFO  WEBrick 1.3.1
[2012-04-20 15:51:07] INFO  ruby 1.9.2 (2011-07-09) [x86_64-linux]
[2012-04-20 15:51:07] INFO  WEBrick::HTTPServer#start: pid=27704 port=9292

port は 9292 になります。
ruby myapp.rb の port 4567と同じ動きです。

productionモードで動かす場合は下記のコマンドになります。
RACK_ENV=production rackup config.ru

Sinatraのルートの最後のスラッシュ

ルートの最後にスラッシュがあってもなくても動くようにしたい場合は、
最後に「/?」をつければ良いです。
http://www.sinatrarb.com/faq.html#slash


例えば、下記のどちらでも動かせるようにしたい場合、
スラッシュなし
get '/hello' do
  "Hello"
end
スラッシュあり
get '/hello/' do
  "Hello"
end

こんなふうに書くだけでどちらにもマッチします!
get '/hello/?' do
  "Hello"
end

2012年4月19日木曜日

Sinatraの環境切り替え

config.ymlといった定義ファイルをdevelopmentモードとproductionモードといったモードで切り替えを行う方法です。

http://www.sinatrarb.com/contrib/config_file.html


下記2行を追加すれば、railsのようにproduction/developmentの記載できます。
require "sinatra/config_file"
config_file 'path/to/config.yml
例えば、こんなconfig.ymlがあったとします。
production:
  server: sinatra_production
  port: 5555
development:
  server: sinatra_dev
  port: 5555
test:
  server: sinatra_test
  port: 5555
settings.serversettings.port でそれぞれのモードに応じた値が取得できます。
settingsはお決まりの用語です。

なお、上記のymlでも下記のymlでも同じ結果になります。
server:
  production: sinatra_production
  development: sinatra_dev
  test: sinatra_test

port: 5555

どちらの記載が良いのかは、定義ファイルの書く内容次第ですね。

Sinatraのホットデプロイ

ファイルを変更するたびに、Ctrl+Cして、再起動していたので、
何かないか探してた所、sinatra-reloaderというものがありました。
http://www.sinatrarb.com/contrib/reloader
$ gem install sinatra-reloader
Fetching: backports-2.5.1.gem (100%)
Fetching: rack-test-0.6.1.gem (100%)
Fetching: eventmachine-0.12.10.gem (100%)
Building native extensions.  This could take a while...
Fetching: sinatra-contrib-1.3.1.gem (100%)
Fetching: sinatra-reloader-1.0.gem (100%)
Successfully installed backports-2.5.1
Successfully installed rack-test-0.6.1
Successfully installed eventmachine-0.12.10
Successfully installed sinatra-contrib-1.3.1
Successfully installed sinatra-reloader-1.0
5 gems installed



ファイルのほうには、こんなふうに書いてあげれば良し。
if development?
  require "sinatra/reloader"
  also_reload File.dirname(__FILE__) + "/Xxxx.rb" ## 一緒にリロードするファイルがあれば
end
この下にはいつも通りの configure… before… get…等が続く。


2012年4月11日水曜日

Sinatraでviewに引数を渡す

Rails同様に:localsを使う
get '/get' do
  res_data = find(x,y)
  erb hello, :locals => {:data => res_data}
end
views/hello.erb
Result:
<%= data %>

2012年4月10日火曜日

Sinatraの起動ポート変更

Sinatra起動時のポートは4567だが、変更する場合は、下記のように -p をつけて起動すれば良い。
$ ruby api.rb  -p 4568
[2012-04-10 18:05:45] INFO  WEBrick 1.3.1
[2012-04-10 18:05:45] INFO  ruby 1.9.2 (2011-07-09) [x86_64-linux]
== Sinatra/1.3.2 has taken the stage on 4568 for development with backup from WEBrick
[2012-04-10 18:05:45] INFO  WEBrick::HTTPServer#start: pid=13966 port=4568
他にもいくつかの起動オプションあり。
$ ruby api.rb  -h
Usage: api [options]
    -p port                          set the port (default is 4567)
    -o addr                          set the host (default is 0.0.0.0)
    -e env                           set the environment (default is development)
    -s server                        specify rack server/handler (default is thin)
    -x                               turn on the mutex lock (default is off)



2012年4月5日木曜日

RubyからMongoへのアクセス

単一のMongoDB
conn = Mongo::Connection.new("localhost",27017)

ReplicaSetsのあるSecondaryに接続
conn = Mongo::Connection.new("localhost",27017, :slave_ok=>true)

ReplicaSetsでMongoDB
conn = Mongo::ReplSetConnection.new(['10.20.30.40:27017','10.20.30.41:27017'], :read => :secondary)
Secondaryが落ちてる場合は、Primaryに接続される。

PrimaryとSecondaryのどちらに接続されているかを確認ができる
conn.read_primary?


参考
http://api.mongodb.org/ruby/current/Mongo/ReplSetConnection.html

Sinatraのロケールファイル

railsみたいにロケールファイルを用意するにはどうすれば良いのだろう?と
調べていたら辿りついたのがこのサイト!ありがとうございます♪
http://d.hatena.ne.jp/ruedap/20110331/ruby_sinatra_i18n_r18n

gemのインストール
$ gem install sinatra-r18n
Fetching: r18n-core-0.4.14.gem (100%)
Fetching: sinatra-r18n-0.4.14.gem (100%)
Successfully installed r18n-core-0.4.14
Successfully installed sinatra-r18n-0.4.14
2 gems installed
ロケールファイルの作成
プロジェクトルート以下に、i18nのフォルダを作成し、ja.ymlやen.ymlといったファイルを作成。

YAMLファイルなので、下記のように記載。
message:
  error1: サーバーが停止しています

呼び出し側の記述下記のrequireを追加して、tオブジェクトを用いて
ロケールファイルの定義を記載するだけで表示!
require 'sinatra/r18n'

t.message.error1

2012年4月2日月曜日

JSONView

Chromeに便利なJSONを整形して表示するプラグインがあったのでメモっておきます

開発元
https://github.com/gildas-lormeau/JSONView-for-Chrome

ダウンロード先
https://chrome.google.com/webstore/detail/chklaanhfefbnpoihckbnefhakgolnmc

sinatraを使ってjsonを返す際に、見やすくなります。

はじめてのSinatra

見よう見まねで、とりあえず
http://www.sinatrarb.com/intro-jp.htmlを試してみた♪
あっさり動いて感動!

gemのインストール
$ gem install sinatra
Fetching: rack-1.4.1.gem (100%)
Fetching: rack-protection-1.2.0.gem (100%)
Fetching: sinatra-1.3.2.gem (100%)
Successfully installed rack-1.4.1
Successfully installed rack-protection-1.2.0
Successfully installed sinatra-1.3.2
3 gems installed
Installing ri documentation for rack-1.4.1...
Installing ri documentation for rack-protection-1.2.0...
Installing ri documentation for sinatra-1.3.2...
Installing RDoc documentation for rack-1.4.1...
Installing RDoc documentation for rack-protection-1.2.0...
Installing RDoc documentation for sinatra-1.3.2...

アプリの作成
# myapp.rb
require 'sinatra'
get '/' do
  'Hello world!'
end

Webサーバーの起動
$ ruby -rubygems myapp.rb
[2012-04-02 16:37:45] INFO  WEBrick 1.3.1
[2012-04-02 16:37:45] INFO  ruby 1.9.2 (2011-07-09) [x86_64-linux]
== Sinatra/1.3.2 has taken the stage on 4567 for development with backup from WEBrick
[2012-04-02 16:37:45] INFO  WEBrick::HTTPServer#start: pid=24126 port=4567

アクセス
http://localhost:4567/