1024tips

WEBエンジニアがLinux,Mac,Rails他のTIPSをまとめます。目指せ1024TIPS!

rails

ActionMailerでヘルパを使う設定

RailsのActionViewの中でapplication_helperで書いたヘルパを使おうとしたらNoMethodErrorになった。以下のようにActionMailerを継承したクラスでヘルパを呼んでやる必要がある。

class FooMailer < ActionMailer::Base
  helper ApplicationHelper

  def bar
  end
end

一瞬はまりかけたのでメモ。 

Railsレシピブック 183の技Railsレシピブック 183の技
著者:高橋 征義
販売元:ソフトバンククリエイティブ
発売日:2008-05-31
おすすめ度:4.5
クチコミを見る

 

windowsでattachment_fuのsize parameterエラーが出る場合

自分もはまりかけたのでメモ。attachment_fuで“Size is not in the list”というエラーが出まくる場合、:sizeで最小値、最大値を指定する必要がある。

http://rupakg.wordpress.com/2008/03/13/attachment_fu-size-parameter-on-windows/

Well, long story short, I have been going crazy trying to make attachment_fu upload a image file greater than 10KB in size on Windows. It keeps showing an error message “Size is not in the list”. Turns out that the size parameter needs to explicitly set to the following:

has_attachment  :content_type => :image, :size => 0.kilobytes..1.gigabytes

The important part is that you have to specify the minimum limit as 0.kilobytes or it will not work. 

Webrickをデーモンとして起動する

Webrickをデーモンとしてサーバに使う方法。さっきの記事ではmongrelが起動するが、Mongrelは開発が止まっていてRails2.3以上のRack対応でセッション周りの管理に追随できなくなってきている。「script/server webrick」でmongrelではなくwebrickを起動できる。さらに-dでログ出力なしになる。

# ruby script/server webrick -d -p 80
=> Booting WEBrick
=> Rails 2.3.2 application starting on http://0.0.0.0:80

Mongrelをデーモンとして起動する

細かいことはいいからとりあえずMongrelをサーバとして動かす必要がある場合。-dでデーモンモード(コンソールにログが出ない)。-pでポート指定。-eを指定しないと-e developmentと同じ。

# ruby script/server -d -p 80
=> Booting Mongrel
=> Rails 2.3.2 application starting on http://0.0.0.0:80
#

Railsのメソッドで引数の数を可変にする

viewのヘルパなど、必要なときだけオプションの引数を受け付けたい場合に便利。options={}でメソッドの引数を可変にできる。


def datetime_select(object_name, method, options = {})
    InstanceTag.new(object_name, method, self, nil, options.delete(:object)).to_datetime_select_tag(options)
end

ちなみにoptions={}で定義した引数はoptions[:key]で参照できる。

「undefined method `quote_ident' for PGconn:Class」エラー@Rails2.3.4+PostgreSQL環境

Rails2.3.2のアプリをRails2.3.4にした所、「undefined method `quote_ident' for PGconn:Class」という見慣れないエラーが。

http://d.hatena.ne.jp/TrinityT/20090831/1251722550 とかhttp://d.hatena.ne.jp/hs9587/20090915/1253008328 を読んだ所、文字通りPostgreSQL用のメソッドがNoMethodになっているようなので以下の記述を追加した。

■config/initializers/new_rails_defaults.rbの修正箇所
以下を冒頭に追加する。冒頭に必要なのは、ActiveRecord初期化前に必要なため。

# for Rails2.3.3 with PostgreSQL
class PGconn
  def self.quote_ident(name)
    '"' + name + '"'
  end
end

Passengerをdevelpmentモードで動かす

開発マシンをApache+Passengerで動かしていてRailsをdevelopment環境で動かしたい場合、次の記述を行う。


ServerName www.myapp.com
DocumentRoot /home/username/myapp/public
RailsEnv development
Railsレシピブック 183の技Railsレシピブック 183の技
著者:高橋 征義
販売元:ソフトバンククリエイティブ
発売日:2008-05-31
おすすめ度:5.0
クチコミを見る

Ruby on Rails 逆引きクイックリファレンス Rails 2.0対応
Ruby on Rails 逆引きクイックリファレンス Rails 2.0対応
著者:大場 寧子
販売元:毎日コミュニケーションズ
発売日:2008-05-31
おすすめ度:4.0
クチコミを見る

RubyGemsのインストールパスを取得する

railsのgemでrequireが失敗するのでインストールパスを調べた。原因は別だったのだが、半年後の自分のためにメモ。

 
$ gem environment
RubyGems Environment:
  - RUBYGEMS VERSION: 1.3.5
  - RUBY VERSION: 1.8.7 (2008-08-11 patchlevel 72) 
[universal-darwin10.0] - INSTALLATION DIRECTORY: /Library/Ruby/Gems/1.8 - RUBY EXECUTABLE: /System/Library/Frameworks/
Ruby.framework/Versions/1.8/usr/bin/ruby - EXECUTABLE DIRECTORY: /usr/bin - RUBYGEMS PLATFORMS: - ruby - universal-darwin-10 - GEM PATHS: - /Library/Ruby/Gems/1.8 - /Users/sakaki/.gem/ruby/1.8 - /System/Library/Frameworks/Ruby.framework/
Versions/1.8/usr/lib/ruby/gems/1.8 - GEM CONFIGURATION: - :update_sources => true - :verbose => true - :benchmark => false - :backtrace => false - :bulk_threshold => 1000 - "install" => "--no-ri --no-rdoc" - :sources => ["http://gems.rubyforge.org/",
"http://gems.github.com/"] - "update" => "--nor --no-rdoc" - REMOTE SOURCES: - http://gems.rubyforge.org/ - http://gems.github.com/

Railsでメールの日本語化

Rails2.2以降でUTF8のメールを日本語化する方法。
→ActionmailerJaプラグインを使う。以上。

http://github.com/kusakari/actionmailer_ja
ActionmailerJa
==============
インストールするだけで、ActionMailer が日本語対応になるプラグインです。 また、携帯電話用のメールテンプレートの振り分け機能も提供します。 Ruby on Rails 2.0 以降に対応しています
Example
=======
*日本語対応。
インストールするだけで、メールが iso-2022-jp で送信されるようになります。(Softbank の携帯電話への送信は UTF-8 になります。)。
 
  Ruby on Rails 逆引きクイックリファレンス Rails 2.0対応Ruby on Rails 逆引きクイックリファレンス Rails 2.0対応
著者:大場 寧子
販売元:毎日コミュニケーションズ
発売日:2008-05-31
おすすめ度:4.0
クチコミを見る

Railsレシピブック 183の技Railsレシピブック 183の技
著者:高橋 征義
販売元:ソフトバンククリエイティブ
発売日:2008-05-31
おすすめ度:5.0
クチコミを見る

Railsで改行を<br>変換する

Railsでコメントなどの複数行のテキストを改行表示したい場合、以下の方法がある。

simple_format(sanitaize @text )

Railsのセッション有効期限を指定する設定

Railsはデフォルトではブラウザを開いている間セッションを維持する。ブラウザが閉じられるとセッションも無効になる。たいていの場合、これで十分。

しかし業務要件で最後に操作してから10分でセッションを切りたい、という場合は次のように設定する。application_controllerでアクセスがある度に有効期限を10分後に更新していく。


Rails2.0系の場合

自前で書く場合

■controllers/application_controller.rb

# limit sessions to 10min.
ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS.update(
  :session_expires => 10.minute.from_now
)

sliding_sessionsプラグインを使う場合

http://squarewheel.wordpress.com/2007/11/03/session-cookie-expiration-time-in-rails/#comment-29


Rails2.3.2以上の場合

内部構造が変わったため、上記の方法は使えなくなった。session_store.rbに書くだけで自動更新される。
■config/intializers/session_store.rb
ActionController::Base.session = {
  :expire_after => 1.minute
}

■参考:
http://squarewheel.pl/posts/3

If you need to set expiration period for sessions through all controllers in your application, simply add the following option to your config/intializers/session_store.rb file:

:expire_after => 60.minutes

If you need to set different expiration time in different controllers or actions, use the following code in action or some before_filter:

request.session_options = request.session_options.dup
request.session_options[:expire_after] = 5.minutes
request.session_options.freeze

Duplication of the hash is needed only because it is already frozen at that point, even though modification of at least :expire_after is possible and works flawlessly.

 Railsレシピブック183の技
Railsレシピブック183の技

NestedAttributes使用時のi18nによるエラーメッセージ日本語化設定

RailsのNestedAttributesを使うと階層化されたモデルを一つのフォームで操作できるようになり便利。NestedAttributes使用時のi18nによるエラーメッセージ日本語化設定についてはまったので自分用メモ。

ポイントはblog.saveした際のメッセージなのでblogの下に「posts_comments_subject」という小文字&アンダーバーでつないだ書式で書くこと。

Blog > Post > Comment.subjectという構造の場合。

ymlの日本語化設定は以下のようになる。
ja-JP:
  attributes:
    blog:
      posts_comments_subject: タイトル
  Railsレシピブック 183の技Railsレシピブック 183の技
著者:高橋 征義
販売元:ソフトバンククリエイティブ
発売日:2008-05-31
おすすめ度:5.0
クチコミを見る

Railsレシピ
Railsレシピ
著者:Chad Fowler
販売元:オライリー・ジャパン
発売日:2006-12-19
おすすめ度:5.0
クチコミを見る

stylesheet_link_tagのスタイルが印刷に反映されない場合

Railsのstylesheet_link_tagではスタイルシートへのリンクを生成できる。しかしデフォルトではmedia="screen"となっているため、スタイルが印刷に反映されない。これを回避するには、:media =>'all'等の指定が必要。
<%= stylesheet_link_tag 'scaffold', 'main', :media => "all" %>

Ruby/Railsで金額を三桁カンマ表示するヘルパ

Rubyにはないが、Railsにはnumber_to_currencyという金額表示用ヘルパが用意されている。currencyとは現地通貨のことでこれを使うと金額を三桁カンマ表示にすることができる。オプションの:precisionは小数点の桁数指定。標準だと2桁指定されているので20,000.00円(2万と00銭)になってしまうので0指定が必要。:formatの%nは数字、:uは単位表示。ここでは:unitで「円」を指定している。
■@charge=20000の場合

請求金額:<%= number_to_currency(@charge,:precision =>0, :format=>"%n%u", :unit=>"円") %>

請求金額:20,000円

 
Railsレシピブック 183の技Railsレシピブック 183の技
著者:高橋 征義
販売元:ソフトバンククリエイティブ
発売日:2008-05-31
おすすめ度:5.0
クチコミを見る

Railsレシピ
Railsレシピ
著者:Chad Fowler
販売元:オライリー・ジャパン
発売日:2006-12-19
おすすめ度:5.0
クチコミを見る

RSpec1.1.5からはautospecコマンドでautotest相当のことができる

「RSpec1.1.5からはautospecでautotest相当のことができる」ということを#rails-tokyoのIRCで教えて貰った。autospec(autotest)を使うと、specファイル保存時にrspecが走る。rake specとかruby script/rails_spec spec/models/testmodel_spec.rbと毎回打つ必要がなくなる。余計なウィンドウ移動が減って、コードに集中できるのはすばらしい!

 

--
12:15 (ysakaki) WindowsXPの環境でRSpeccのautotest動かせてる方いますか?
12:19 (yoshuki_) こんにちは、1.1.5からautospecコマンドになってますよ
12:22 (ysakaki) なんと!
12:23 (walf444) autospecついてるけど中でautotestをsystemでよんでるだけと角谷さんがいってたような気がする
12:25 (ysakaki) でけました!
--

walf444さんありがとう!


The Rspec Book: Behaviour Driven Development With Rspec, Cucumber, and Friends
The Rspec Book: Behaviour Driven Development With Rspec, Cucumber, and Friends
著者:David Chelimski
販売元:Pragmatic Bookshelf
発売日:2009-10
クチコミを見る
 

RailsのForm.seriarizeでremote_functionの:withにフォームの値を設定する

Railsのremote_functionではPost値を:withでいちいち指定する必要がある。 フィールドの数が多い場合は大変だ。

そういう場合、prototype.jsにForm.serialize('フォームのID')でフォームの値をname1=value1&name2=value2形式にしてくれる関数が便利である。

 

   1  <%= javascript_include_tag "prototype" %>
   2  <script language="JavaScript">
   3  function newArticle(){
   4      <%= remote_function(:url => {:action => :new},
   5                           :update => 'list',
   6                           :with => "Form.serialize('article')"
   7      ) %>
   8  }
   9  </script>

Ajax on RailsAjax on Rails
著者:Scott Raymond
販売元:オライリー・ジャパン
発売日:2007-07-24
おすすめ度:5.0
クチコミを見る
Railsレシピブック 183の技Railsレシピブック 183の技
著者:高橋 征義
販売元:ソフトバンククリエイティブ
発売日:2008-05-31
おすすめ度:5.0
クチコミを見る
 

Railsでテスト環境にdb:fixtures:loadするには

毎回検索しているのでメモ。RAILS_ENVでload先を指定する。

rake db:fixtures:load FIXTURES=table1,table2 RAILS_ENV=test

Ruby on Rails 逆引きクイックリファレンス Rails 2.0対応Ruby on Rails 逆引きクイックリファレンス Rails 2.0対応
著者:大場 寧子
販売元:毎日コミュニケーションズ
発売日:2008-05-31
おすすめ度:4.0
クチコミを見る
 

gem install でローカルファイルからインストールするオプション

たまにrubyforgeが重くてgemがインストールできないことがある。 仕方ないので直接rubyforgeからgemをダウンロードしてローカルインストールする。

gem install rspec --local

のように--localを指定すれば良い。ただし依存するgemも一式ダウンロードしておく必要があることに注意。

Railsレシピブック 183の技Railsレシピブック 183の技
著者:高橋 征義
販売元:ソフトバンククリエイティブ
発売日:2008-05-31
おすすめ度:5.0
クチコミを見る

Railsレシピ
Railsレシピ
著者:Chad Fowler
販売元:オライリー・ジャパン
発売日:2006-12-19
おすすめ度:5.0
クチコミを見る
 

Railsのredirect_toでアンカータグを指定する

:ahchorで指定する。

redirect_to (:controller=>:ins, :action=>:show,:id=>8,:anchor=>'hoge'))

#→http://localhost:3000/ins/show/8#hoge

Railsレシピブック 183の技Railsレシピブック 183の技
著者:高橋 征義
販売元:ソフトバンククリエイティブ
発売日:2008-05-31
おすすめ度:5.0
クチコミを見る

Railsでサーバの起動モードを指定するには

Railsでproductionモード以外で動かしたいが起動時にオプション指定するのが面倒な場合、設定ファイルに書く方法が用意されている。
config/environments/boot.rb内でRAILS_ENV='development'などと指定する。
RailsデプロイRailsデプロイ
著者:Ezra Zygmuntowicz
販売元:オライリージャパン
発売日:2009-03-16
クチコミを見る

訪問者数
  • 今日:
  • 昨日:
  • 累計: