开发者

Rails 3: Get current view's path helper?

开发者 https://www.devze.com 2023-03-15 09:02 出处:网络
I\'m interested in creating a standard for my layouts where each view would be wrapped in a container named according to a specific convention.

I'm interested in creating a standard for my layouts where each view would be wrapped in a container named according to a specific convention.

Just for instance, if I had:

resources :foos

I would want the views to be wrapped in divs like so:

<div id="foos_view"> foos#index here </div>
<div id="foo_view"> foos#show here </div>
<div id="new_foo_view"> foos#new here </div>
<div id="edit_foo_view"> foos#edit here </div>

So, basically I'd like to use the route name, but substitute 'path' for 'view'.

My question is, is there some way to g开发者_高级运维et the route name for the current view?

Ie. if my request is example.com/foos/new is there anything I can call in the view or controller that would return new_foo_path?

Thanks!


I can't think of an easy way to do this, as the path helpers simply do a call to path_for() and fill in the required params, so there's no method call to do it in reverse.

However, this is Ruby, so it's fairly easy to write a quick helper to return the string that you want. The current controller name can be accessed via controller.controller_name and the action name via controller.action_name.

Something like this should do you:

def html_id

   string = ""

   if controller.action_name =~ /new|edit/
      string += controller.action_name + "_"
   end

   if controller.action_name =~ /index|create/
     string += controller.controller_name
   else
     string += controller.controller_name.singularize
   end

   return string += "_view"

 end
0

精彩评论

暂无评论...
验证码 换一张
取 消