RailsにWebサーバ起動起動処理を追加してみました

INDEX PAGE

RailsにWebサーバ起動起動処理を追加してみました


Loggerをラップした独自ログ出力クラスや
Syslogに対して障害通知を行うクラスなどを
Webサーバ起動時に初期化して、グローバル変数に格納しておきたいと考えていたのですが
こちらの実装を行ってみました。

まずは、
(RailsRoot)/lib/common/
というディレクトリを作成し、ここを共通機能ようモジュール配置場所としました。
そして、この直下に「initializer.rb」なるソースを作成しました。

Rubyプラグインを見ると、共通ロジックはlibの下に書くのが正しいみたいだったので
こうしてみたのだけど、果たしてこれが本当にRuby流なのか?

ソースの中身は次のような感じ。

require 'lib/common/logging/com_loging'
require 'lib/common/notify/syslog_notify'

module Initializer

##ログオブジェクトの初期化
$comlog = ComLoging.new
$comlog.info_log("########## ログオブジェクトの初期化に成功しました ##########")

##警告通知オブジェクトの初期化
$notify = SyslogNotify.new
$notify.info_notify("Webサーバ、障害通知オブジェクトの初期化に成功しました")

end

/logging/com_loging.rb
/notify/syslog_notify.rb
の2ファイルは、前述のWebサーバ起動時に初期化したロジックです。

こんな形で初期化ロジックをまとめておいて
後は
(RailsRoot)/config/common/environment.rb
に下記のように追記します。

# Be sure to restart your server when you modify this file
##文字コードの設定
$KCODE = 'u'

# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'production'

# Specifies gem version of Rails to use when vendor/rails is not present

##Railsバージョンの設定
RAILS_GEM_VERSION = '2.0.2' unless defined? RAILS_GEM_VERSION

# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
##アプリケーション初期化処理の実行
require File.join(RAILS_ROOT, "lib", "common", "initializer")


Railsは起動時に下のサイトのように起動するようです。
http://doruby.kbmj.com/yoppi_on_rails/20080215/_rails_20_
というわけで、この方法で大丈夫そうです。


なお、最初requireの記述を間違えてWebサーバが起動しなかったのですが
その時のエラー表示がしたのような感じで
原因がなんのことかわからずに苦しみました。

=> Booting Mongrel (use 'script/server webrick' to force WEBrick)
=> Rails application starting on http://127.0.0.1:4002
=> Call with -d to detach
=> Ctrl-C to shutdown server
Starting Mongrel listening at 127.0.0.1:4002
Starting Rails with development environment...
Exiting
c:/ruby/lib/ruby/gems/1.8/gems/rails-2.0.2/lib/commands/servers/mongrel.rb:16: warning: already initialized constant OPTIONS
c:/ruby/lib/ruby/gems/1.8/gems/rails-2.0.2/lib/commands/servers/mongrel.rb:19: undefined method `options' for []:Array (NoMethodError)
from c:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:32:in `gem_original_require'
from c:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:32:in `require'
from c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:496:in `require'
from c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:342:in `new_constants_in'
from c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:496:in `require'
from c:/ruby/lib/ruby/gems/1.8/gems/rails-2.0.2/lib/commands/server.rb:39
from c:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require'
from c:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require'
from ./script/server:3
from -e:2:in `load'
from -e:2

INDEX PAGE