Railsではアクション内にConst変数を宣言することができない?
以下のようなコードをアクションに書いたらシンタックスエラーになってしまった。
Item = Struct.new("Item", :value, :name) case type when 'select' item.new(0, "選択して下さい") when 'search' item.new(0, "すべて") else item.new(0, "すべて") end
エラーの出力内容は以下の通り。
SyntaxError (./script/../config/../app/controllers/hoge_controller.rb:55: dynamic constant assignment
定数は一度宣言してから代入しようとはしてないし…そもそも宣言でエラーだし。
グーグル先生に聞いてみるとRails Tracで同様の問題が報告されていた。
http://dev.rubyonrails.org/ticket/4287
回答の肝となる部分を引用。
Ruby doesn't allow assigning class constants within method bodies, hence you get the "dynamic constant assignment" exception. It's not exclusive to Struct nor to Rails:
http://dev.rubyonrails.org/ticket/4287
つまり、メソッドの中ではConst変数は宣言できないと言う事らしい。
def e Hoge = "aa" end #=> SyntaxError: compile error (irb):2: dynamic constant assignment Hoge = "aa" ^ from (irb):3
なるほど…。
と言うわけで、アクションメソッドの外にStructのサブクラスの宣言を移したら無事に動いた。
結論として、Railsではアクション内にConst変数を宣言することができない、のではなくRubyではメソッド内でConst変数を宣言することができない、と言う事なのね。