Forum: Ruby on Rails How to go DRY?

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.
Yash (Guest)
on 2006-03-22 10:46
We are creating a website for creating and maintaining communities. When
members of a community are listed, we show their summary in a TABLE. So
we have written a _member.rhtml partial to show this summary for that
member. To show the memberlist we do
render :partial => member, :collection => @members

Now the problem is the row displayed for every member by the _member
partial, may differ depending on the context. For instance, if we are
listing them under a community, we want to show a BLOCK button next to
each member, to allow the user to block other members from that
community. When displaying members in a general list, not under a
community, we want to show an INVITE button against every member to add
him as a friend in the user's Friends list.
There are a number of other cases, wherein the buttons or additional
info shown for each member is different depending on the context.

In such cases how do we code the _member partial to take care of all
different possible ways to show a member?
In general is there a guideline on how to make sure we Don't Repeat
Ourselves?

-Yash
Tom L. (Guest)
on 2006-03-25 06:11
(Received via mailing list)
On 3/22/06, Yash <removed_email_address@domain.invalid> wrote:
> In such cases how do we code the _member partial to take care of all
> different possible ways to show a member?
> In general is there a guideline on how to make sure we Don't Repeat
> Ourselves?

You could parameterize the partial and use calls like this:

render :partial => member, :collection => @members, :locals => {
:invite => true }

Then you would conditionally show or hide parts of the partial based
on the parameters:

<tr>
<!-- other fields -->
<% if invite %><td><!-- invite button --></td><% end %>
<% if block %><td><!-- block button --></td><% end %>
</tr>

I have old code which did this, and I received errors about nil
variables for when :invite was not passed, but this may have been
addressed, and is also generally easy to prevent: <% if
defined?(invite) and invite %> to default to off, and <% if
!defined?(invite) or invite %> to default to on.

I hope this helps, and that I didn't make any mistakes in my samples. :P

> -Yash

Sincerely,

Tom L.
http://AllTom.com/
http://GadgetLife.org/
This topic is locked and can not be replied to.