ヘルパメソッドを簡単に機能拡張する方法
ここでは、直前で話題のlink_if_authorized_unless_currentを実際に追加定義してみる。
機能拡張する前に考えたこと
もし、link_if_authorizedと全く同じ機能を提供するlink_if_authorized_unless_currentを定義するにはどうすれば良いか?
link_if_authorizedのソースを確認
user_engineのrdocでソースを確認してみると、link_if_authorizedは、以下のように定義されている。
def link_if_authorized(name, options = {}, html_options = {}, *params, &block) ...(途中省略)... end
同じ機能のlink_if_authorized_unless_currentを定義
link_if_authorizedと全く同じ機能のメソッドは、app/helpers/application_helper.rbで、以下のように定義できる。
-
-
- link_if_authorizedのソースで引数の並びを確認して、同じ引数の並びのlink_if_authorized_unless_currentメソッドを定義する。
- メソッド定義の中で、引数をそのまま利用して、link_if_authorizedメソッドを再実行すれば、同じ機能になるはず。
-
module ApplicationHelper ...(途中省略)... def link_if_authorized_unless_current(name, options = {}, html_options = {}, *params, &block) link_if_authorized(name, options, html_options, *params, &block) end end
機能拡張
それでは、機能拡張するためには、このメソッド定義の中で自由に処理を追記すればいい。以下のように定義してみた。
-
-
- コントローラー名、アクション名がリンクURLと同じ場合は、:id => 'current'オプションを追加して、link_if_authorizedを実行する。
-
module ApplicationHelper ...(途中省略)... def link_if_authorized_unless_current(name, options = {}, html_options = {}, *params, &block) if controller.controller_name == options[:controller] && controller.action_name == options[:action] html_options.merge!(:id => 'current') end link_if_authorized(name, options, html_options, *params, &block) end end
活用
link_if_authorized_unless_currentを利用して、_menu.rhtmlは以下のようになった。メソッド名を、link_if_authorized_unless_currentに変更しただけ。これだけで、現在のページと同じURLのリンクは、強調表示されるようになる。とてもスッキリした!
...(途中省略)... <div id="navcontainer"> <ul id="navlist"> <%= link_if_authorized_unless_current 'CSVリスト', {:controller => 'csvs', :action => 'list'}, :wrap_in => "li" %> <%= link_if_authorized_unless_current 'パスワード変更', {:controller => 'user', :action => 'change_password'}, :wrap_in => "li" %> <%= link_if_authorized_unless_current '権限管理', {:controller => 'role', :action => 'list'}, :wrap_in => "li" %> <%= link_if_authorized_unless_current 'ユーザー管理', {:controller => 'user', :action => 'list'}, :wrap_in => "li" %> <%= link_if_authorized_unless_current 'アクセス権管理', {:controller => 'permission', :action => 'list'}, :wrap_in => "li" %> <%= link_if_authorized_unless_current 'ログアウト', {:controller => 'user', :action => 'logout'}, :wrap_in => "li" %> </ul> </div>
-
-
- その後、メソッド名が長すぎるので、link_if_authorized_currentに変更した。意味的にも:id="current"を追加するので、こっちの方が良い感じ。
-
これからは、もっとヘルパメソッドを活用できそうだ!