Forum: Ruby on Rails DRYing up between Helper and Controller

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Kip (Guest)
on 2007-07-29 04:40
(Received via mailing list)
I have a few small methods as part of my authorisation scheme,  These
mostly get used by controllers, but sometimes I want a template to
call them too.

For example, there are methods called is_editor?, is_author? and
is_publisher? currently in application.rb.

I am including/excluding elements for navigation in the user interface
based upon these roles.  Therefore I want one definition of these
methods that "everyone" can use.

Whats the right rails way to achieve this?

Cheers, --Kip
Roderick v. (Guest)
on 2007-07-29 15:34
Kip wrote:
> I have a few small methods as part of my authorisation scheme,  These
> mostly get used by controllers, but sometimes I want a template to
> call them too.
>
> For example, there are methods called is_editor?, is_author? and
> is_publisher? currently in application.rb.
>
> I am including/excluding elements for navigation in the user interface
> based upon these roles.  Therefore I want one definition of these
> methods that "everyone" can use.
>
> Whats the right rails way to achieve this?

I'd issue "helper_method :is_editor?" in my application controller.
Others prefer a construction like so:

class ApplicationHelper
  def for_editors
    yield if is_editor?
  end
end

Now you can do:

<% for_editors do -%>
  Editors only!
<% end -%>

Whichever is prettier is a matter of preference I suppose.

--
Roderick van Domburg
http://www.nedforce.nl
This topic is locked and can not be replied to.