after_create と after_save の違い

その名の通り、after_createは新しいレコードが作成された時、たった一度だけ呼び出される。after_saveはsaveが走る度に呼び出される。

というわけで、下記のように使い分ける。

  • 作成時にたった一度しか実行しない処理 → after_create
  • 更新の度に実行したい処理 → after_save

もちろん、after_saveはcreate時も実行されます



参照
http://stackoverflow.com/questions/6422199/what-is-the-difference-between-after-create-and-after-save-and-when-to-use-w

pkillコマンドでプロセス名からkillする

プロセスをkillする際、今までは

ps aux | grep netbeans

なんてやって、いちいちプロセス番号を打ち込んでkillしていましたが、pkillコマンドを使うと名前からプロセスをkillすることができます。

pkill -KILL -f netbeans

ちなみに-fはフルコマンドラインでマッチさせるオプションです。

OPTIONS
       -c     Suppress normal output; instead print a count of matching processes.

       -d delimiter
              Sets the string used to delimit each process ID in the output (by default a newline).  (pgrep only.)

       -f     The pattern is normally only matched against the process name.  When -f is set, the full command line is used.

       -g pgrp,...
              Only match processes in the process group IDs listed.  Process group 0 is translated into pgrep's or pkill's own process group.

       -G gid,...
              Only match processes whose real group ID is listed.  Either the numerical or symbolical value may be used.

       -l     List the process name as well as the process ID. (pgrep only.)

       -n     Select only the newest (most recently started) of the matching processes.

       -o     Select only the oldest (least recently started) of the matching processes.

       -P ppid,...
              Only match processes whose parent process ID is listed.

       -s sid,...
              Only match processes whose process session ID is listed.  Session ID 0 is translated into pgrep's or pkill's own session ID.

       -t term,...
              Only match processes whose controlling terminal is listed.  The terminal name should be specified without the "/dev/" prefix.

       -u euid,...
              Only match processes whose effective user ID is listed.  Either the numerical or symbolical value may be used.

       -U uid,...
              Only match processes whose real user ID is listed.  Either the numerical or symbolical value may be used.

       -v     Negates the matching.

       -x     Only match processes whose name (or command line if -f is specified) exactly match the pattern.

       -signal
              Defines the signal to send to each matched process.  Either the numeric or the symbolic signal name can be used.  (pkill only.)

NetBeans 7.x + rvm + fast debugger + ruby1.9.3

NetBeans 7.x + rvm + fast debuggerの記事を書きましたが、そこではruby1.9.2が対象で、ruby1.9.3では動きませんでした。

どうやらfast debuggerがrubyのバージョンに依存しているのが原因らしいです。
この問題ですが、最新のgemを導入することであっさり解決しました。


尚、この記事の手順でのgemのインストール先は以下のようになります。

rvmでつくったgemsetのgem path以下にruby-debuggergem一式を入れる。
プロジェクトで必要なgemは慣習どおり、app/vendor/bundle以下に入れる。

NetBeansの導入などについてはNetBeans 7.x + rvm + fast debuggerの記事を見てもらえるといいと思います。

Step1
.rvmでruby1.9.3に切り替える(ruby1.9.3のインストールはこちらの記事をどうぞ)

rvm use 1.9.3-p125 --default

Step2.gemsetを作成する(僕の場合はプロジェクトに応じてgemsetを作成しているけれど、いらないと思うならなくてもいいと思う)

rvm gemset create myapp

Step3.gemsetを指定する(複数のプロジェクトで使いまわすなら、globalに入れておくのがいいかもしれない)

rvm gemset use myapp

Step4.ruby-debbugのgem一式をインストールする(ruby-1.9.3-p125を対象にしています。p125以外を使う場合はgistの内容を書き換えてください。)

bash < <(curl -L https://raw.github.com/gist/2767067)

Step5.Ruby Platform Manager(ツール > Ruby Platforms > ruby-1.9.3-p125を選択)でGem PathにStep3で指定したgemのパスを指定する

/home/bismar/.rvm/gems/ruby-1.9.3-p125@myapp

Step6. デバッカの設定
NetBeans 7.x + rvm + fast debuggerの記事Step5. デバッカの設定を参照してください。

Rails3 css、js 404 Not Found! 静的ファイルが読み込まれない!

検証環境(VM)でアプリを実行したところ、js、css、イメージファイルなどの静的ファイルが読み込まれず、404 Not Foundになってしまいました。

これの原因は、config/environments/production.rb内の設定で、config.serve_static_assetsの値がプロダクション環境ではデフォルトでfalseになっているためでした。

# Disable Rails's static asset server
# In production, Apache or nginx will already do this
config.serve_static_assets = false


Rails guideによると、この値は静的ファイルをRails自身がサーブするか、NginxやApacheなどのアプリケーションがサーブするかでtrueとfalseを切り替えます。静的ファイルはNginxやApacheが供給すべきなのでプロダクションモードのテストの時など以外にはtrueにしないでね。ということらしいです。
今回は自分しか使わないVMだったのでtrueにしましたが、プロダクション環境ではNginxやApacheのconfファイルで設定しましょう。

config.serve_static_assets configures Rails itself to serve static assets. Defaults to true, but in the production environment is turned off as the server software (e.g. Nginx or Apache) used to run the application should serve static assets instead. Unlike the default setting set this to true when running (absolutely not recommended!) or testing your app in production mode using WEBrick. Otherwise you won´t be able use page caching and requests for files that exist regularly under the public directory will anyway hit your Rails app.


参考:
http://guides.rubyonrails.org/configuring.html

rvmでruby1.9.3をインストールしたらエラーが出た。

rvmでruby1.9.3をインストールしようとして、下記コマンドを打ったところ、

rvm install 1.9.3-p125

と言う具合で、エラーが出てインストールできない。

bismar@BISMAR-PC:~/test/myapp$ rvm install 1.9.3-p125
Installing Ruby from source to: /home/bismar/.rvm/rubies/ruby-1.9.3-p125, this may take a while depending on your cpu(s)...

ruby-1.9.3-p125 - #fetching 
ruby-1.9.3-p125 - #downloading ruby-1.9.3-p125, this may take a while depending on your connection...
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 9505k  100 9505k    0     0  3414k      0  0:00:02  0:00:02 --:--:-- 3820k
ruby-1.9.3-p125 - #extracting ruby-1.9.3-p125 to /home/bismar/.rvm/src/ruby-1.9.3-p125
ruby-1.9.3-p125 - #extracted to /home/bismar/.rvm/src/ruby-1.9.3-p125
ruby-1.9.3-p125 - #configuring 
ruby-1.9.3-p125 - #compiling 
ruby-1.9.3-p125 - #installing 
Removing old Rubygems files...
-e:1: Use RbConfig instead of obsolete and deprecated Config.
Installing rubygems dedicated to ruby-1.9.3-p125...
Installing rubygems for /home/bismar/.rvm/rubies/ruby-1.9.3-p125/bin/ruby
ERROR: Error running 'GEM_PATH="/home/bismar/.rvm/gems/ruby-1.9.3-p125:/home/bismar/.rvm/gems/ruby-1.9.3-p125@global:/home/bismar/.rvm/gems/ruby-1.9.3-p125:/home/bismar/.rvm/gems/ruby-1.9.3-p125@global" GEM_HOME="/home/bismar/.rvm/gems/ruby-1.9.3-p125" "/home/bismar/.rvm/rubies/ruby-1.9.3-p125/bin/ruby" "/home/bismar/.rvm/src/rubygems-1.6.2/setup.rb"', please read /home/bismar/.rvm/log/ruby-1.9.3-p125/rubygems.install.log
WARN: Installation of rubygems did not complete successfully.
ruby-1.9.3-p125 - adjusting #shebangs for (gem irb erb ri rdoc testrb rake).
ruby-1.9.3-p125 - #importing default gemsets (/home/bismar/.rvm/gemsets/)
Install of ruby-1.9.3-p125 - #complete


解決方法として、まずrvmのアップデートを行った。

rvm get latest
rvm reload
rvm version

しかしエラーがでる。

bismar@BISMAR-PC:~/test/myapp$ rvm get latest

Original installed RVM version:

rvm 1.6.9 by Wayne E. Seguin (wayneeseguin@gmail.com) [https://rvm.beginrescueend.com/]

rvm-
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0curl: (60) SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
More details here: http://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
 of Certificate Authority (CA) public keys (CA certs). If the default
 bundle file isn't adequate, you can specify an alternate file
 using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
 the bundle, the certificate verification probably failed due to a
 problem with the certificate (it might be expired, or the name might
 not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
 the -k (or --insecure) option.
md5sum: /home/bismar/.rvm/archives/rvm-.tar.gz: そのようなファイルやディレクトリはありません
tar (child): /home/bismar/.rvm/archives/rvm-.tar.gz: open 不能: そのようなファイルやディレクトリはありません
tar (child): Error is not recoverable: exiting now
tar: Child returned status 2
tar: Error is not recoverable: exiting now
/tmp/29338: 71 行: cd: /home/bismar/.rvm/src/rvm-: そのようなファイルやディレクトリはありません
chmod: `./scripts/install' にアクセスできません: そのようなファイルやディレクトリはありません
/tmp/29338: 行 75: ./scripts/install: そのようなファイルやディレクトリはありません

Installed RVM version:

rvm 1.6.9 by Wayne E. Seguin (wayneeseguin@gmail.com) [https://rvm.beginrescueend.com/]

どうもrvm get latestではなくrvm get headでなければいかないらしい。

rvm get head
rvm reload
rvm install 1.9.3-p125

ruby1.9.3のインストールを再実行

bismar@BISMAR-PC:~/test/myapp$ rvm remove ruby-1.9.3-p125
Removing /home/bismar/.rvm/src/ruby-1.9.3-p125...
Removing /home/bismar/.rvm/rubies/ruby-1.9.3-p125...
Removing ruby-1.9.3-p125 aliases...
Removing ruby-1.9.3-p125 wrappers...
Removing ruby-1.9.3-p125 environments...
Removing ruby-1.9.3-p125 binaries...
bismar@BISMAR-PC:~/test/myapp$ rvm install ruby-1.9.3-p125
Fetching yaml-0.1.4.tar.gz to /home/bismar/.rvm/archives
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  460k  100  460k    0     0   223k      0  0:00:02  0:00:02 --:--:--  309k
Extracting yaml-0.1.4.tar.gz to /home/bismar/.rvm/src
Configuring yaml in /home/bismar/.rvm/src/yaml-0.1.4.
Compiling yaml in /home/bismar/.rvm/src/yaml-0.1.4.
Installing yaml to /home/bismar/.rvm/usr
Installing Ruby from source to: /home/bismar/.rvm/rubies/ruby-1.9.3-p125, this may take a while depending on your cpu(s)...

ruby-1.9.3-p125 - #fetching 
ruby-1.9.3-p125 - #extracting ruby-1.9.3-p125 to /home/bismar/.rvm/src/ruby-1.9.3-p125
ruby-1.9.3-p125 - #extracted to /home/bismar/.rvm/src/ruby-1.9.3-p125
ruby-1.9.3-p125 - #configuring 
ruby-1.9.3-p125 - #compiling 
ruby-1.9.3-p125 - #installing 
Retrieving rubygems-1.8.24
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  371k  100  371k    0     0   831k      0 --:--:-- --:--:-- --:--:-- 3199k
Extracting rubygems-1.8.24 ...
Removing old Rubygems files...
Installing rubygems-1.8.24 for ruby-1.9.3-p125 ...
Installation of rubygems completed successfully.
ruby-1.9.3-p125 - adjusting #shebangs for (gem irb erb ri rdoc testrb rake).
ruby-1.9.3-p125 - #importing default gemsets (/home/bismar/.rvm/gemsets/)
Install of ruby-1.9.3-p125 - #complete 

インストール完了!


参考:
http://d.hatena.ne.jp/stog/20110326/1301168745
http://stackoverflow.com/questions/7967723/error-while-installing-ruby-1-9-3

mysqlのテーブルからデータをcsvファイルにインポート/エクスポートする

CSVファイルからデータをテーブルにインポート

mysql> load data local infile "hoge.csv" into table table_name fields terminated by ',';

テーブルのデータをCSVファイルへエクスポート

mysql> select * from table_name into outfile "hoge.csv" fields terminated by ',';

NetBeans 7.x + rvm + fast debugger これでもう困らない!

NetBeans7.0以降rubyのサポートが打ち切られました。それから7.1がリリースされ、7.2リリースを控えている現在も未だに僕はNetBeans派です。
ただ、サポート以前と違って設定にコツがいるようになりました。NetBeans7.0以降、毎回行なっている設定を書き留めておきたいと思います。

Rails3以降、僕の開発環境はこんな感じです。尚、本記事はruby gemを
bundle install --path vendor/bundleコマンドでapp/vendor/bundle以下にインストールする前提です。

  • OS ・・・ Mac OS X (職場の環境ではUbuntuで同じ設定を行なっています)
  • rubyのバージョン管理 ・・・ rvm
  • rubyのバージョン ・・・ 1.9.2
  • Rails ・・・ Rails3
  • gemの管理 ・・・ bundler
  • デバッカ ・・・ fast debugger


Step0. 古いNetBeansの設定ファイルを消しておく

my-MacBook:~ bismar$ ls -all | grep .netbeans
.netbeans-derby/        .netbeans/
.netbeans-registration/ 
my-MacBook:~ bismar$ rm -rf .netbeans*


Step1. NetBeansの入手

NetBeans本体をインストールします。http://netbeans.org/downloads/index.htmlから、最もファイルサイズの軽いPHPバンドルをダウンロードします。


Step2. NetBeansRuby on Rails開発のためのプラグインを入れる

1. NetBeansrubyサポートは終了しましたが、Ruby開発用のプラグインが有志によって作成されているので手動でインストールします。
http://jruby.org.s3.amazonaws.com/downloads/community-ruby/community-ruby_7_1_preview1.zip
2. ダウンロードしたファイルを適当なフォルダに解凍します。
3. NetBeansのツールバーより、「ツール」⇒「プラグイン」⇒「ダウンロード済み」⇒「プラグインの追加」から、解凍したフォルダのxxx.nbmファイルをすべて読み込みます。
4. 「インストール済み」一覧から、「Ruby and Rails」を選択します。この時、Ruby and Rails」以外は選択しないことをおすすめします。

これでNetBeans本体の設定は完了です。


Step3. gemのインストール

ここからはgemの設定になります。
Gemfileに下記のgemの記述を追加し、bundle install --path vendor/bundleコマンドでgemのインストールを行います。

gem 'ruby-debug-ide19'
gem 'ruby-debug19'


Step4. rubyプラットフォームの設定

NetBeansのツールバーより、「ツール」⇒「Ruby Platforms」⇒「Ruby 1.9.2-pxxx」を選択 ⇒「Gem Home」にapp/vendor/bundle以下にインストールしたgemのパスを指定します。
例:/Users/bismar/app/vendor/bundle/ruby/1.9.1
Gem Pathからは不要なパスを削除しておきましょう。僕の場合はrvmを使っていますが、今回はgemsetを作成していないので、/Users/bismar/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/gems/1.9.1/gems以下にbundler gemとrake gemが入っています。なので、Gem Pathでは
例:/Users/bismar/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/gems/1.9.1/gems
だけを指定しています。


Step5. デバッカの設定

ここでデバックモードで起動してみてください。下記の様なエラーが出るはずです。

Fast Debugger (ruby-debug-ide 0.4.9) listens on :50111
	/Users/bismar/app/vendor/bundle/ruby/1.9.1/gems/ruby-debug-ide19-0.4.12/lib/ruby-debug-ide.rb:123:in `debug_load'
	/Users/bismar/app/vendor/bundle/ruby/1.9.1/gems/ruby-debug-ide19-0.4.12/lib/ruby-debug-ide.rb:123:in `debug_program'
	/Users/bismar/app/vendor/bundle/ruby/1.9.1/gems/ruby-debug-ide19-0.4.12/bin/rdebug-ide:87:in `<top (required)>'
	/Users/bismar/app/vendor/bundle/ruby/1.9.1/bin/rdebug-ide:19:in `load'
	/Users/bismar/app/vendor/bundle/ruby/1.9.1/bin/rdebug-ide:19:in `<main>'
Uncaught exception: no such file to load -- script/rails

script/railsファイルが認識されていないのが原因の様です。
ruby-debug-ide.rbファイルの123行目あたりの下記行を書き換えます。

bt = debug_load(`pwd`.chomp+'/script/rails', options.stop, options.load_mode)
# コメントアウト bt = debug_load(Debugger::PROG_SCRIPT, options.stop, options.load_mode) 

これで動くはずです。。動かない場合は一度NetBeansを再起動してみてください。


参考:
http://www.oiax.jp/rails/zakkan/how_to_install_rails_plugin_on_netbeans_7_1.html
http://stackoverflow.com/questions/4899422/how-to-import-ror-project-to-netbeans
http://yasrails.blog33.fc2.com/blog-entry-13.html

追記2012/5/13
rakeタスクが動かない問題は未だ解決していない。コンソールからは動かせるから放置してるけど。