【ruby on rails】ApplicationControllerクラスで定義したメソッドをヘルパーとして利用する

全てのviewで利用したい変数がある場合には、ApplicationControllクラスでクラス変数として定義してあげればいいが、その変数にviewからアクセスする方法がわからなかった。

これまでは、Controllerクラスを指定してアクセスしていたんだけど、Authenticated_Systemのlogged_in?とかcurrent_userメソッドなど、ApplicationControllerクラスにIncludeしたメソッドが利用できてるから、どうやってんだろと見てみたら以下のようなおまじないを見つけた。

def self.included(base)
  base.send :helper_method, :current_user, :logged_in?
end

includeした時に走るメソッドのようだけど(てか、includeでメソッドが呼べるのも感動)、なにやら、helper_methodに利用させたいメソッドをsendしてる。

てなわけで、同じようにhelper_methodにsendしてみたら出来た!

class ApplicationController < ActionController::Base
  send :helper_method, :all_categories
  @@categories = Feed.find(:all, :order => 'id')
  def all_categories
    @@categories
  end
end

タグ:[ruby on rails

このログへのコメント(0件)

コメント投稿フォーム

コメント

※半角英数字だけのコメントは投稿できません。

トラックバック

関連ログ