Archive for category Ruby on Rails

Ruby on Rails覚えるだ Rails application failed to start properlyが出てどうにもならない

さくらインターネットにデプロイしようとしてにっちんもさっちんも行かなくなっている今日この頃です。

で、非常にいい感じの情報をゲットしたのでシェアしたい。

デプロイにおいて、500や403エラーもやたらと出るが、多分最後に出てくるのが
Rails application failed to start properly
ではないだろうか。

Application error
Rails application failed to start properly"

こんなの。
ログにも何もでないし、問題解決のしようがない。
そこで銀の銃弾とはならないものの、どこが悪いのかおぼろげに
見える素敵手法がある。
プロジェクトのpublic/フォルダに移動し、

ruby dispactch.cgi

を行うと、rails内でのエラーを吐いてくれるので、
お試しあれ。

ウチの場合はこんなん出た。原因究明はまだ。

%ruby dispatch.cgi
/home/xxxx/rails/xxxx/vendor/rails/actionpack/lib/action_controller/cgi_process.rb:22:in `__send__': undefined method `env_table' for nil:NilClass (NoMethodError)
    from /home/xxxx/rails/xxxx/vendor/rails/actionpack/lib/action_controller/cgi_process.rb:22:in `dispatch_cgi'
    from /home/xxx/rails/xxxx/vendor/rails/actionpack/lib/action_controller/dispatcher.rb:101:in `dispatch_cgi'

    from /home/xxxxx/rails/xxxx/vendor/rails/actionpack/lib/action_controller/dispatcher.rb:27:in `dispatch'
    from dispatch.cgi:12

ただ、railsのバージョンによっては自動に生成されないので注意が必要。
そういう時はやや見苦しいが、ダミープロジェクトを作成し、

rails -D dummy

と入れることでpublic内にdispatch.cgiが作成されるので、それをコピペすると良い。

dispatch.cgiの一行目の

#!/usr/bin/ruby

を自分の環境に合わせることもお忘れなく。

参照リンク
http://www.hostingrails.com/faq#rails_failed_to_start 正直激お役立ちサイトなので暇を見ては訳す。

Ruby on Rails覚えるだ RSSフィードを作成。 詰まったところ大全

例えばブログサイトやサイトのニュース関連等、何かしら定期的に更新される内容をRSSで
配信したいと思った場合の方法を紹介。

まぁただ実際のRSS出力の部分については各所で取り扱われているので、うまくいかなかったりして詰まったあたりと純粋な手順を中心に紹介。他所の例の通りにやってるのにうまくいかないという人は参考になるかも。

例ではxxxxコントローラーのindexをRSSフィード元とする。

まず、ControllerのIndexを編集。

def index
    処理
   
    respond_to do |format|
      format.html # index.html.erb
      format.rss  { render :layout => false }
    end
  end

を追加。
どうもRails2.0以降ならこれはやらなくてもいいようなのだが、コントローラーがLayoutを使用している場合、それがRSSにも反映されてしまうので、
それを防ぐために上記処理を追加する。どうしても書きたくない場合は、

layout "レイアウト名", :except => :アクション

等でそのアクションのレイアウトしようをとめることができるが、HTMLでのレイアウトも使えなくなってしまうので専用のアクションを作る必要がある。

そしてViewの中にindex.rss.builderを作成。
実際のBuilderの中身については各所で色々ちゃんとしたものがあるので今回は割愛。

さて、できたRSSフィードにアクセスしてみようとすると

class XxxxController <ApplicationController
 
No route matches "/index.rss"

def index

と出てしまう。もうなにがわるいやら。

ちなみに、index.html.erbには問題なくアクセスできることは確認。
サーバーの再起動等も行ってみたが改善せず。

どうもフォーマットの部分がうまく伝わっていないようだということまでは分かるが、どう直せばいいのかわからなかった。
で、最終的にはRoutes.rbで

map.rss 'index.rss', :controller => 'xxxx', :action => 'index', :format => 'rss'

とすることでごまかした。

なんとなく
map.connect

をうまくすれば何とかなりそうなのだが。

参考リンク
http://rubyist.g.hatena.ne.jp/rochefort/20090120
http://railscasts.com/episodes/87-generating-rss-feeds
http://rubist.blog77.fc2.com/blog-entry-64.html

Ruby on Rails覚えるだ ActiveRecordのfindでdatetimeを使って検索したい。

RubyonRailsを使ってあれこれ作業中、とあるテーブルのdatetime型のデータから特定の月のみに合致するものを抜き出したくなった。

例としては、ブログアプリを作っていて、ある年とある月のエントリだけを抜き取って表示したい、とかそんな感じだ。

Entry.find(:all, :conditions=>)

で条件を絞ればいいというところまではすぐ分かるが、datetimeの場合どのように絞ればいいのかがわからない。
通常文字列みたいに「xxxx =>"yyy"」という風にも、数値のように「xxx => yyy」とするわけにもいかないので、はまってしまった。

こういう時は困ったときのStackOverflow頼み。さっそく聞いてみた
http://stackoverflow.com/questions/1576027/how-to-use-datetime-in-the-condtions-of-a-find-count-in-ruby-on-rails
なんと投稿して三分で答が返ってきた。

さすが世界中のエンジニアのすくつですね。

で、例えば検索元のデータがdatetimeの場合、

xxx.find( :all, :conditions => ["month(yyy) = ? AND year(yyy) = ?", zzz.month, zzz.year] )

このようにすれば合致する
yyyが検索対象のカラム、zzzが検索する条件となる。

ちなみに検索条件が固定の場合はこんな感じ。

xxx.find( :all, :conditions => ["month(yyy) = ? AND year(yyy) = ?", "09", "2009"] )

当然findじゃなくてcountでも同じことができる。

どーでもいいことだけどやっぱり海外じゃ月、日、年なんだなぁと思った。
たぶん日本人的には

xxx.find( :all, :conditions => ["year(yyy) = ? AND month(yyy) = ?", "2009", "09"] )

さくらインターネットでRubyonRailsを使用する その2 ~デプロイ~

前回に引き続き、さくらインターネットへRubyonRailsのプロジェクトをデプロイする。

とりあえず試したい!という人は、適当にどこかからサンプルプロジェクトを引っ張ってきましょう。
WindowsならInstantRailsにCookbookなんかのサンプルがあるので、それを使うと良い良い。
ただ、前回の環境構築で設定したバージョンが合っている事を確認する必要がある。

まず、データベースの設定から。

開発環境時に使っていたdatabase.ymlはあくまでローカル用に最適化された設定なので、あまり役に立たない。
さくらインターネット側で使うデータベースの情報は、さくらインターネットのサーバーコントロールパネル内の
データベースの設定を参照することで入手できる。

まだデータベースを作成していない場合はさくっと作ってしまいましょー。
で、下記画像にある情報とdatabase.ymlとの対応は以下の通り。

WS000099

production:

  adapter: mysql
  encoding: utf8
  database: ①
  username: ②
  password: ④
  host: xxxxxxxxx.db.sakura.ne.jp

プロジェクトのデータベース構造をマイグレートする。

rake db:migrate RAILS_ENV="production"

見事成功。

次は実行環境もちゃんと設定する。
config/environment.rbの先頭行に以下を追加。

# Be sure to restart your server when you modify this file
$LOAD_PATH.push("$HOME/local/lib/ruby/site_ruby/1.8")
$LOAD_PATH.push("$HOME/local/lib/ruby")
ENV['GEM_HOME'] ||= '$HOME/local/lib/ruby/gem'
ENV['RAILS_RELATIVE_URL_ROOT']="/test"

ENV['RAILS_RELATIVE_URL_ROOT']=の先は作成したRailsのプロジェクト名にすること。
また上記各種パスは前回~/.cshrcに設定したものと同じにすること。

で、さっそくいつもどおりにサーバーを起動してみる。

ruby script/server

500 Internal Server Errorが出た。

ちょっと調べてみたところ、ちゃんとproductionで起動してない模様。
たぶんどっかのファイルで設定できると思うのだけど、横着して引数で何とかする。

ruby script/server -e production

まぁ、ただ実際の運用でアドレスに:3000なんて出すのはちょっと頂けないので、Apacheを使った方法においおい切り替えたほうがいいのかも。

参考リンク
http://iwatakenichi.blogspot.com/2007/08/ruby-on-rails-on-sakura-part3.html
http://nyon2.net/archives/2009/01/ruby-on-railsruby-on-rails.html

さくらインターネットでRubyonRailsを使用する その1 ~開発環境とのバージョンを合わせる~

さくらインターネットはご存知だろうか?

メールサーバやSSHログインして結構自由にできちゃうレンタルサーバなんかを
かなり安価な値段で使えるインフラ屋さんである。
昔はさくらのフレッツ接続って固定IPが標準でついてくる超激安ISPもやっていたのだが、
大分前から新規募集を停止してしまっている。
…何時の日か復活して欲しいものである。

話がそれた。で、このさくらインターネット、結構RubyonRailsをデプロイする先としては有名で、
色んなところで取り上げられている。もちろんここでも取り上げる。
特にローカル環境で開発したアプリケーションをさくらにアップして動かせるようにするということを目的に行う。

そのためただ環境を構築するだけでなく、ちゃんと開発環境とあわせるようにする。

さくらインターネットでのRubyonRailsのデプロイ方法をメモ。まずは開発環境とのバージョン合わせから。
実際のデプロイ作業に関しては次回。

まず、RailsやRubyが初期状態ではさくらインターネット側の更新に影響されてしまうので、
ローカルでバージョンを固定して使用できるようにする。

開発していた環境と同じRubyとRailsにする。
この場合は

Ruby=1.8.6
Rails=2.2.2

とする。
このあたりは各自の事情とか状況とか欲望とかに合わせて設定してくだちい。

ちょっと場所が場所なのでファイルの場所に注意する。

mkdir src
cd src/

wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.6-p383.tar.gz

tar zxvf ruby-1.8.6-p383.tar.gz

cd ruby-1.8.6-p383

./configure --prefix=$HOME/local

make

make install

vi ~/.cshrc

setenvと書かれているところに

setenv RUBYLIB $HOME/local/lib/ruby/1.8:$HOME/local/lib/ruby
setenv GEM_HOME $HOME/local/lib/ruby/gem

を追加する。一行目がRubyのパスで、二行目がこれから入れるRubyGemsのパスとなる。

set path = ( $HOME/local/bin $HOME/local/lib/ruby/gem/bin /sbin /bin /usr/sbin /usr/bin /usr/local/sbin /usr/local/bin $HOME/bin )

setenv  EDITOR  vi
setenv  PAGER   more
setenv  BLOCKSIZE       K
setenv  PKG_DBDIR       ~/db/pkg
setenv RUBYLIB $HOME/local/lib/ruby/site_ruby/1.8:$HOME/local/lib/ruby
setenv GEM_HOME $HOME/local/lib/ruby/gem

で、次はGemsのインストール。
cd $HOME/src/

wget http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz

tar zxvf rubygems-1.3.5.tgz

cd rubygems-1.3.5

ruby setup.rb

そして仕上げのRailsインストール。
バージョンを指定してインストールすることを忘れない。
gem install rails -v2.2.2 --include-dependencies

%ruby -v
ruby 1.8.6 (2009-08-04 patchlevel 383) [i386-freebsd7.1]

%rails --version
Rails 2.2.2

うまくいったようだ。ではさっそくデプロイ前にテストしてみる。

rails test
/home/xxxxxxx/local/lib/ruby/gem/gems/rails-2.2.2/bin/../lib/rails_generator/options.rb:32:in `default_options': undefined method `write_inheritable_attribute' for Rails::Generator::Base:Class (NoMethodError)
        from /home/xxxxxxx/local/lib/ruby/gem/gems/rails-2.2.2/bin/../lib/rails_generator/base.rb:90
        from /home/xxxxxxx/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
        from /home/xxxxxxx/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'

        from /home/xxxxxxx/local/lib/ruby/gem/gems/rails-2.2.2/bin/../lib/rails_generator.rb:34
        from /home/xxxxxxx/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
        from /home/xxxxxxx/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'

        from /home/xxxxxxx/local/lib/ruby/gem/gems/rails-2.2.2/bin/rails:13
        from /home/xxxxxxx/local/lib/ruby/gem/bin/rails:19:in `load'
        from /home/xxxxxxx/local/lib/ruby/gem/bin/rails:19

…うまくいかないのが醍醐味だよねー

いつもの如くググりんぐ。

require 'rubygems'
require 'activesupport'

を試してみよとのこと。

irb
require 'rubygems'
=> true
require 'activesupport'
LoadError: no such file to load -- iconv

どうやら参考サイトと同様の現象のよう。安心した。

で、対処作。
先ほどRubyをインストールするときに展開したフォルダへ移動する。

cd $HOME/src/ruby-1.8.6-p383/ext/iconv/

ruby extconf.rb --prefix=$HOME --with-iconv-dir=/usr/local

make

make install

/usr/bin/install -c -m 0755 iconv.so /home/xxxxxxx/local/lib/ruby/site_ruby/1.8/i386-freebsd7.1

と表示されれば成功。では改めて

cd $HOME/rails/

rails test
      create 
      create  app/controllers
      create  app/helpers
      create  app/models
      create  app/views/layouts
      create  config/environments
      create  config/initializers
      create  config/locales
      create  db
        ~省略~
      create  public/javascripts/dragdrop.js
      create  public/javascripts/controls.js
      create  public/javascripts/application.js
      create  doc/README_FOR_APP
      create  log/server.log
      create  log/production.log
      create  log/development.log
      create  log/test.log

成功した。

そして起動確認。
普通に

ruby script/server

でいつものようにhttp://サーバー名:3000でおなじみのウェルカム画面が表示されるはず。

デーモン化。

ruby script/server -d

停止させたい場合は通常のサーバと同じように

ps aux

でPIDを調査し


kill -KILL PID

で停止させる。-KILLオプションをつけないと停止しないので注意。

他サイトでは上記手段ではなくさくらインターネットでしかしないような/htaccessの変更や
シンボリックリンクを張るという手順を見かけるが、ありゃ一体なんなんだろう…。

とりあえず今回の最低限の環境構築は終了。

次回は実際のアプリケーションをデプロイします。

参考サイト
http://tomonori855.sakura.ne.jp/recipe/2006/05/ruby_on_rails.html
http://www.fishowl.com/web/cat21129514/index.html
http://blog.proj.jp/ituki/20090107.html
http://t100life.blog121.fc2.com/blog-entry-148.html

Redmine(Rails)をApacheと連携させたい Phusion Passenger導入

Railsの開発において面倒な点として、Mongrelやら何やらを通してサーバを起動しないといけない点である。
別にそれだけなら数あるデーモンの一つというだけで済むが、問題はRailsプロジェクトごとにポートが新しく
必要になることだ。起動するたびにポートが埋まってしまうのは大変面倒である。特に常駐でRedmineが動いている
サーバなのだ、常時ポート3000は埋まっている状態だ。ローカルでちょっと遊ぶくらいには良いかもしれないが、
実際の運用サーバ等に組み込んだときにどんどんセキュリティに穴を開けてしまうのは非常によろしくない。
できれば3000だってあけたくない。

ので、そういった面倒を回避するためにPhusion Passengerを導入する。
これを導入することにより、わざわざruby script/serverなんてしなくても、3000番ポートを
あけなくてもRailsアプリケーションが、しかもいくつでも立ち上げられるようになるのだ。
これには運用の簡略化以外にもレスポンスの向上も望めるそうなので、ちゃきちゃき入れたい。

ではまず本体のPassengerを導入。

gem install passenger

次にApaccheとのモジュール

passenger-install-apache2-module

対話形式でインストールが進む。
Apacheをインストールしていない場合は足りないもののリストアップとインストール方法を教えてくれるので、
それにしたがってやれば問題ない。

何も入ってなかったらこれでいいはず。

yum install gcc-c++ httpd httpd-devel apr-devel

インストール終了後、以下のメッセージが表示される。

The Apache 2 module was successfully installed.

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

   LoadModule passenger_module /usr/lib/ruby/gems/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so
   PassengerRoot /usr/lib/ruby/gems/1.8/gems/passenger-2.2.5
   PassengerRuby /usr/bin/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を押すと流れてしまうので、今のうちにコピーしておくと楽。
なお、これはたぶん環境によって生成されるものが違うので、上のをコピーしてもうまくいかないやも。

Enterを押すとさらに以下が表示される。virtualhostの設定が表示される。

Deploying a Ruby on Rails application: an example

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

   <VirtualHost *:80>
      ServerName www.yourhost.com
      DocumentRoot /somewhere/public    # <-- be sure to point to 'public'!
   </VirtualHost>

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

  /usr/lib/ruby/gems/1.8/gems/passenger-2.2.5/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.

これでインストールは終了なので、さっき指示された通りにファイルをいじりませう。

vim /etc/httpd/conf/httpd.conf

ファイルの最終行に上で出力された文を追加する。

LoadModule passenger_module /usr/lib/ruby/gems/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so
   PassengerRoot /usr/lib/ruby/gems/1.8/gems/passenger-2.2.5
   PassengerRuby /usr/bin/ruby

   <VirtualHost *:80>
      ServerName www.yourhost.com ←DNSサーバ名や分からない、ないならIPそのものを
      DocumentRoot /somewhere/public    ←Redmineのルート+さらにpublicを足したもの
   </VirtualHost>

また、これによりファイルの実行がMongrelではなくApacheによって行われるため、いくつかのファイルの所有権を移す必要がある。
Redmineのトップフォルダ内で

chown -R apache:apache files log tmp config/environment.rb

そしてApacheを再起動する。

/etc/rc.d/init.d/httpd restart

http://ServerName
にアクセスすると、以前ruby /script/serverと同じ画面が!

下記サイト参照
http://redmine.jp/tech_note/apache-passenger/

G5のMacOSX上のAptanaでhtml.erbファイルを開くとAptanaが落ちる場合の対処

原因は不明であるが、Aptana1.5.1のRadRailsでhtml.erbファイルを開くと100%アプリケーションがクラッシュするという現象に遭遇。
しかもググってもそれらしい解決策は見つからず。しばし悪戦苦闘した。
RubyonRailsを扱う際に色々と面倒なので、対策を検討した。
Aptanaの再インストールも試してみたが効果はなかった。
ちなみに現象はIntelMacやWindowsでは再現しない。
この辺で報告はされているようだがまだ解決されてない様子。

で、解決策。
どうもRadRails内のAptana ERB Editorが原因のようなので、これを使わないようにすれば良いわけだ。
拡張子がerbだった場合はそれとはべつの、普通のエディッタで開くようにすれば良い。
…まぁ、どうしてもERBエディッタ使いたいって人には向かないけど、とりあえず誤ってerbファイル開いたせいでAptana全部クラッシュさせてしまう
恐怖からは解放される。

方法としてはまず上部メニューからAptanaStudioを選択し、環境設定>General>Editors>FileAssociationsにて「*.erb」を登録し、デフォルトのエディタをAptanaERBEditorにする。

参考画像
ERBeditor1

Aptanaで拡張子ごとに開くエディッタを自分好みのものに変えることも可能なので、そういうときにも有効だ。
ちなみにWindowsの場合はウィンドウ>設定で上記図と同じようになる。

CentOSにredmine 導入 二周目

二週目、今回は奇麗なやり方。

実際には元のサーバはどうにかこうにか動かせるようになってしまって、
今更戻すわけにはいかないので、今回はAWSのCentOSイメージを使って検証。

AMI-ID:ami-10b55379 Manifest:cent53-base/ami-centos5.3-base.manifest.xml

を使用する。

こういう検証のやり方は結構便利だ。そのうち実機サーバーのイメージを作ってそれを
EC2で動かしてテストすればさらに便利そう。

では何事もなかったように最初から。(AWSにしたのでインストールしたものとか全部やり直し)

一応、再びRubyとRailsのバージョンあわせから。

yum install -y mysql-server mysql-devel

wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.6-p383.tar.gz

tar zxvf ruby-1.8.6-p383.tar.gz

cd ruby-1.8.6-p383

./configure --prefix=/usr

make

checkinstall

rpm -ivh --nomd5 /usr/src/redhat/RPMS/i386/ruby-1.8.6-1.i386.rpm

checkinstallってなんやねんって人は前の記事を参考。

また、既にRubyをインストールしちゃってて競合が起きてる場合で、
yumでインストールしている人はアンインストールしませう。

yum remove ruby ruby-libs ruby-irb ruby-rdoc ruby-devel

でうまくいくはず。

*ただし、既に他のバージョンに依存するものがある場合は要注意。

次にRubyGemsをインストール

wget http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz

tar zxvf rubygems-1.3.5.tgz

cd rubygems-1.3.5

ruby setup.rb

Railsのインストール。記録用にログとか残す。
Redmineが使用するRailsバージョンは2.2.2なので、指定してインストールする。

gem install rails --include-dependencies -v2.2.2
Successfully installed activerecord-2.2.2
Successfully installed actionpack-2.2.2
Successfully installed actionmailer-2.2.2
Successfully installed activeresource-2.2.2
Successfully installed rails-2.2.2
5 gems installed
Installing ri documentation for activerecord-2.2.2...
Installing ri documentation for actionpack-2.2.2...
Installing ri documentation for actionmailer-2.2.2...
Installing ri documentation for activeresource-2.2.2...
Installing ri documentation for rails-2.2.2...
Installing RDoc documentation for activerecord-2.2.2...
Installing RDoc documentation for actionpack-2.2.2...
Installing RDoc documentation for actionmailer-2.2.2...
Installing RDoc documentation for activeresource-2.2.2...
Installing RDoc documentation for rails-2.2.2...

…残す意味ないような

Mongrelインストール。こっちもついでに。

gem install mongrel
Successfully installed gem_plugin-0.2.3
Successfully installed daemons-1.0.10
Successfully installed cgi_multipart_eof_fix-2.5.0
Successfully installed mongrel-1.1.5
4 gems installed
Installing ri documentation for gem_plugin-0.2.3...
Installing ri documentation for daemons-1.0.10...
Installing ri documentation for cgi_multipart_eof_fix-2.5.0...
Installing ri documentation for mongrel-1.1.5...
Installing RDoc documentation for gem_plugin-0.2.3...
Installing RDoc documentation for daemons-1.0.10...
Installing RDoc documentation for cgi_multipart_eof_fix-2.5.0...
Installing RDoc documentation for mongrel-1.1.5...

mkdir /var/redmine

cd /var/redmine

svn checkout http://redmine.rubyforge.org/svn/trunk/ .

次にMysqlのRedmine用データベースを作成する。

mysql -u root
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

にゅ?
ググってみるとmysqlが起動してない模様。そりゃ接続できんね。

/etc/rc.d/init.d/mysqld start

ついでに起動時に動くよう設定。

chkconfig mysqld on
chkconfig --list mysqld
mysqld          0:off   1:off   2:on    3:on    4:on    5:on    6:off

んだば再度

mysql -u root
Welcome to the MySQL monitor.  Commands end with ; or ¥g.
Your MySQL connection id is 2
Server version: 5.0.45 Source distribution

Type 'help;' or '¥h' for help. Type '¥c' to clear the buffer.

mysql> create database redmine character set utf8;
Query OK, 1 row affected (0.00 sec)
mysql> exit
Bye

ここで明示的にredmineデータベースをUTF8に設定しておかないと色々文字化けで
苦しんだりするかもしれないので注意しましょう。

で、次はRedmineの設定を弄る。

サンプル用の設定ファイルをコピーして使う。
usernameとpasswordは先ほど決めたものに変更、developmentとtestのdatabaseをredmine
にするのは、元のままだと同名のデータベースを作らなければならず、Redmineでは最初から
運用するため使わないので無駄となる。よって運用用のデータベースと同じにしてしまう。

cp config/database.yml.example config/database.yml

以下のようにデータベースの設定を行う。

production:
  adapter: mysql
  database: redmine
  host: localhost
  username: root
  password:
  encoding: utf8
  socket: /var/lib/mysql/mysql.sock

development:
  adapter: mysql
  database: redmine
  host: localhost
  username: root
  password:
  encoding: utf8

test:
  adapter: mysql
  database: redmine
  host: localhost
  username: root
  password:
  encoding: utf8

まあ、実際にはProductionしか使わないのであるが、後学のために
三つとも書いておく。今後のRailsプロジェクトでコピペに使えるし。
databaseのところ書き換え忘れてエラー出しそうである。

Railsのデータベースのマイグレーション

rake db:migrate RAILS_ENV="production"

!!! The bundled mysql.rb driver has been removed from Rails 2.2. Please install the mysql gem and try again: gem install mysql.
rake aborted!
no such file to load -- mysql

マタデスカ

gem install mysql

では再度

rake db:migrate RAILS_ENV="production"

==  Setup: migrating ==========================================================
-- create_table("attachments", {:force=>true})

省略

==  FixMessagesStickyNull: migrating ==========================================
==  FixMessagesStickyNull: migrated (0.0005s) =================================

あっさり成功

次はデフォルトデータの読み込み

rake load_default_data RAILS_ENV="production"
(in /var/redmine)

Select language: bg, bs, ca, cs, da, de, el, en, es, fi, fr, gl, he, hu, it, ja, ko, lt, nl, no, pl, pt, pt-BR, ro, ru, sk, sl, sr, sv, th, tr, uk, vi, zh, zh-TW [en] ja

さて、いよいよサーバーを起動する

ruby script/server

Status: 500 Internal Server Error Content-Type: text/html
500 Internal Server Error

…?

コンソールの方を確認。

A secret is required to generate an integrity hash for cookie session data. Use config.action_controller.session =
{ :session_key => "_myapp_session", :secret => "some secret phrase of at least 30 characters" } in config/environment.rb

yum -y install expect

mkpasswd -l 32

vim config/environment.rb

config.action_mailer.perform_deliveries = false

config.action_controller.session = { :session_key => "_myapp_session", :secret => "さっき生成した文字列" }

ruby script/server

成功。
いやー一週目の苦労はなんだったんだ…

後はAdmin:Adminでログインし、パスワードの変更、ユーザーの登録を行う。
ログイン後MyAccount<Languageで日本語を選択すると日本語化できる。

下記サイトを参照。
http://blog.apecell.com/2008/04/02/id/38
http://blog.livedoor.jp/leaveanest/archives/846257.html
http://uprush.net/2009/06/redmine%E3%82%92centos5%E3%81%AB%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB/
http://d.hatena.ne.jp/snusmum/20090827/1251380110
http://blog.livedoor.jp/maru_tak/archives/50664746.html

CentOSにredmine 導入 一周目

ソフト開発するにあたって、レポジトリを含むWiki的なものはあると非常に楽である。
チームからみた場合互いの連携に使え、後から言った言わないの水掛輪を防げるし、
個人から見ても逐一書き込んでおけば色々見返せて便利だ。

以前の会社ではTracを使っていたが、あんまり評判は良くないようだ。
ので、Redmineを導入してみる。

で、一回目やった時には正直あまりにぐだぐだだったのであげたくなかったのだが、失敗した時の解決策の方が
奇麗な成功より参考になりそうなので、一応記述。

インストールの参考にはならないと思うので、奇麗なインストール例は次回の記事で。

yum install -y mysql-server mysql-devel

yumでRubyをインストールしてもいいのだけど、執筆時点でCentOSが
とってくるRubyは1.8.5。このまま行くといろいろ問題が発生するので、
ここは1.8.6にしておく。

wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.6-p383.tar.gz

tar zxvf ruby-1.8.6-p383.tar.gz

cd ruby-1.8.6-p383

./configure --prefix=/usr

make

checkinstall

rpm -ivh --nomd5 /usr/src/redhat/RPMS/i386/ruby-1.8.6-1.i386.rpm

checkinstallってなんやねんって人は前の記事を参考。

また、既にRubyをインストールしちゃってて競合が起きてる場合で、
yumでインストールしている人はアンインストールしませう。

yum remove ruby ruby-libs ruby-irb ruby-rdoc ruby-devel

でうまくいくはず。

*ただし、既に他のバージョンに依存するものがある場合は要注意。

次にRubyGemsをインストール

wget http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz

tar zxvf rubygems-1.3.5.tgz

cd rubygems-1.3.5

ruby setup.rb

Railsのインストール。

gem install rails --include-dependencies

記録用にログとか残す。

Successfully installed activesupport-2.3.4
Successfully installed activerecord-2.3.4
Successfully installed rack-1.0.0
Successfully installed actionpack-2.3.4
Successfully installed actionmailer-2.3.4
Successfully installed activeresource-2.3.4
Successfully installed rails-2.3.4
7 gems installed
Installing ri documentation for activesupport-2.3.4...
Installing ri documentation for activerecord-2.3.4...
Installing ri documentation for rack-1.0.0...
Installing ri documentation for actionpack-2.3.4...
Installing ri documentation for actionmailer-2.3.4...
Installing ri documentation for activeresource-2.3.4...
Installing ri documentation for rails-2.3.4...
Installing RDoc documentation for activesupport-2.3.4...
Installing RDoc documentation for activerecord-2.3.4...
Installing RDoc documentation for rack-1.0.0...
Installing RDoc documentation for actionpack-2.3.4...
Installing RDoc documentation for actionmailer-2.3.4...
Installing RDoc documentation for activeresource-2.3.4...
Installing RDoc documentation for rails-2.3.4...

…残す意味ないような

Mongrelインストール。こっちもついでに。

gem install mongrel
Successfully installed gem_plugin-0.2.3
Successfully installed daemons-1.0.10
Successfully installed cgi_multipart_eof_fix-2.5.0
Successfully installed mongrel-1.1.5
4 gems installed
Installing ri documentation for gem_plugin-0.2.3...
Installing ri documentation for daemons-1.0.10...
Installing ri documentation for cgi_multipart_eof_fix-2.5.0...
Installing ri documentation for mongrel-1.1.5...
Installing RDoc documentation for gem_plugin-0.2.3...
Installing RDoc documentation for daemons-1.0.10...
Installing RDoc documentation for cgi_multipart_eof_fix-2.5.0...
Installing RDoc documentation for mongrel-1.1.5...

Redmine用のディレクトリを作成(この場合は /var/redmine、どこでも良い)して、
SVNをつかってRedmineをチェックアウトする

mkdir /var/redmine

cd /var/redmine

svn checkout http://redmine.rubyforge.org/svn/trunk/ .

次にMysqlのRedmine用データベースを作成する。

mysql -u root
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

にゅ?
ググってみるとmysqlが起動してない模様。そりゃ接続できんね。

/etc/rc.d/init.d/mysqld start

ついでに起動時に動くよう設定。

chkconfig mysqld on
chkconfig --list mysqld
mysqld          0:off   1:off   2:on    3:on    4:on    5:on    6:off

んだば再度

mysql -u root
Welcome to the MySQL monitor.  Commands end with ; or ¥g.
Your MySQL connection id is 2
Server version: 5.0.45 Source distribution

Type 'help;' or '¥h' for help. Type '¥c' to clear the buffer.

mysql> create database redmine character set utf8;
Query OK, 1 row affected (0.00 sec)
mysql> exit
Bye

ここで明示的にredmineデータベースをUTF8に設定しておかないと色々文字化けで
苦しんだりするかもしれないので注意しましょう。

で、次はRedmineの設定を弄る。

サンプル用の設定ファイルをコピーして使う。
usernameとpasswordは先ほど決めたものに変更、developmentとtestのdatabaseをredmine
にするのは、元のままだと同名のデータベースを作らなければならず、Redmineでは最初から
運用するため使わないので無駄となる。よって運用用のデータベースと同じにしてしまう。

cp config/database.yml.example config/database.yml

以下のようにデータベースの設定を行う。

production:
  adapter: mysql
  database: redmine
  host: localhost
  username: root
  password:
  encoding: utf8
 socket: /var/lib/mysql/mysql.sock

development:
  adapter: mysql
  database: redmine
  host: localhost
  username: root
  password:
  encoding: utf8

test:
  adapter: mysql
  database: redmine
  host: localhost
  username: root
  password:
  encoding: utf8

まあ、実際にはProductionしか使わないのであるが、後学のために
三つとも書いておく。今後のRailsプロジェクトでコピペに使えるし。
databaseのところ書き換え忘れてエラー出しそうである。

Railsのデータベースのマイグレーション

rake db:migrate RAILS_ENV="production"
(in /var/redmine)
Missing the Rails 2.2.2 gem. Please `gem install -v=2.2.2 rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed

これだから発展途上の言語は嫌いデース。

解説しておくと、Redmineは開発者が作った環境に依存しているため、特にRailsのバージョンなんかは露骨にその動きに影響されるわけで、
こちらのバージョンが違うとこういう問題が起きるのですね。対処法としては、
1)Railsのバージョンを合わせる。
2)エラーメッセージにあるようにRAILS_GEM_VERSIONを自分のRailsバージョンに合わせる。

とりあえず2)でいってみましょう。
今後2.2.2固定でやっていくとは限らないし

わぁ、さっきログとっておいたのが役に立ったね♪

vim /config/enviroment.rb

# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.2.2' unless defined? RAILS_GEM_VERSION

RAILS_GEM_VERSION = '2.3.4' unless defined? RAILS_GEM_VERSION

以上のように変更。変更バージョンは適切に変更してください。

rails -v

とかで調べて。

rake db:migrate RAILS_ENV="production"
(in /var/redmine)
rake aborted!
A key is required to write a cookie containing the session data. Use config.action_controller.session = { :key => "_myapp_session", :secret => "some secret phrase" } in config/environment.rb

(See full trace by running task with --trace)

わぁまた知らんエラーが

注意書きに則り、

vim config/environment.rb

下記を末尾に追加する

config.action_controller.session = { :key => "_myapp_session", :secret => "適当な英数字" }

再再度挑戦

rake db:migrate RAILS_ENV="production"
(in /var/redmine)
!!! The bundled mysql.rb driver has been removed from Rails 2.2. Please install the mysql gem and try again: gem install mysql.
rake aborted!
no such file to load -- mysql

はいだらーーー!

まぁ、解決策がすぐ分かるエラーを出してくれる分にはいいですね、ええ。

*実はここでruby1.8.5だと1.8.6以降じゃないとインストールできないとか抜かされるので、ちゃんと1.8.6にしないと駄目なのだ。

gem install mysql

成功。
では再々々々挑戦

rake db:migrate RAILS_ENV="production"

(in /var/redmine)
==  Setup: migrating ==========================================================
-- create_table("attachments", {:force=>true})
   -> 0.1660s
-- create_table("auth_sources", {:force=>true})

省略

成功した。
*実はここでmysql-develをインストールしてなくて色々うまくいかなったのだが、
そこは割愛。

デフォルトデータの読み込み
言語設定ではjaを選択

rake load_default_data RAILS_ENV="production"
(in /var/redmine)

Select language: bg, bs, ca, cs, da, de, el, en, es, fi, fr, gl, he, hu, it, ja, ko, lt, nl, no, pl, pt, pt-BR, ro, ru, sk, sl, sr, sv, th, tr, uk, vi, zh, zh-TW [en] ja

さて、いけたようなので、いよいよ起動してみる。

ruby script/server
=> Booting WEBrick
=> Rails 2.3.4 application starting on http://0.0.0.0:3000
/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/dependencies.rb:443:in `load_missing_constant': uninitialized constant ApplicationController (NameError)
    from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/dependencies.rb:80:in `const_missing'

    from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/dependencies.rb:92:in `const_missing'
    from /var/redmine/app/controllers/account_controller.rb:18
    from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'

    from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
    from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/dependencies.rb:158:in `require'

    from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/dependencies.rb:265:in `require_or_load_without_engine_additions'
    from /var/redmine/vendor/plugins/engines/lib/engines/rails_extensions/dependencies.rb:124:in `require_or_load'

     ... 18 levels...
    from /usr/lib/ruby/gems/1.8/gems/rails-2.3.4/lib/commands/server.rb:84
    from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
    from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'

    from script/server:3

ググる。どうも本格的に2.3で運用するのはあんまり向いてないらしい。Railsをプロジェクトごとに素直に切り替えた方がよかったのかなぁと後悔。

cd app/controllers

どうやらコントローラの一つの名前が変更されている模様。

mv application.rb application_controller.rb

ruby script/server

が、これでもエラーが出てしまいうまくゆかず。
その後色々やってもうまくいきませんでした。
もう少しがんばればできたかも知れないが、問題の根幹はRails2.2.2用のRedmineを無理やり2.3.4で動かそうとしたことなのである。…あの時、Railsをあわせるを選んでおけば…

GAME OVER

以下二週目に続く、まさかここまでそのままやった人はいないと思うが、やってしまった記録としてどう対処するかも記録する。
まぁ、ぶっちゃけ下記の手順を行うことによりRedmineが正常に動くようになる。

まず、先ほど変えてしまったコントローラの名前を元に戻し、

mv application_controller.rb application.rb

Redmineの環境設定でRailsのバージョンを2.2.2に。

vim /config/enviroment.rb
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.4' unless defined? RAILS_GEM_VERSION

RAILS_GEM_VERSION = '2.2.2' unless defined? RAILS_GEM_VERSION

最初から2.2.2を選んだ場合の手順書についてはこちら

下記サイトを参照。
http://blog.apecell.com/2008/04/02/id/38
http://blog.livedoor.jp/leaveanest/archives/846257.html
http://uprush.net/2009/06/redmine%E3%82%92centos5%E3%81%AB%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB/
http://d.hatena.ne.jp/snusmum/20090827/1251380110
http://blog.livedoor.jp/maru_tak/archives/50664746.html

Ruby on Rails覚えるだ 2 Mongrelのデーモン起動とシャットダウン

環境に関してはCentOS5.3にて

Railsで何かを作成した際、ウェブ上からアクセスできるようにするためには一般的にMongrelを起動する必要がある。
いわゆる

ruby script/server

だ。

ただこれをこのままやってしまうと使用したコンソールが塞がってしまうので、あまりよろしくない。
ので、

ruby script/server -d

と-dオプションをつけることによりデーモン化することができる。これによりコンソールが操作可能となる。

さて、その後なんらかの理由でMongrelをシャットダウンしたくなったとき、killコマンドを使うのがよい。
しかしpsコマンドを打ってもmongerlプロセスがない。よし、再起動だ!ではさすがにアレ過ぎるので、
やり方を紹介。

ps ax | grep ruby

と入力すると、起動しているMongrelが表示される。大体こんな感じ

2721 ?        Sl     0:31 /usr/bin/ruby /usr/bin/mongrel_rails start -p 3000 -a 0.0.0.0 -e development -P /var/redmine/tmp/pids/mongrel.pid -d

この最初に表示されるのがプロセスIDなので、これの場合だったら

kill 2721

とすれば、再起動せずともMongrelのみを停止させることができる。