please advise on my helper for table cells

21 views
Skip to first unread message

Jedrin

unread,
Oct 8, 2015, 10:39:41 AM10/8/15
to Ruby on Rails: Talk

 I have a helper like this:

  def table_elements(qualifier, count)
    if qualifier
      yield
    else
      return ("<td></td>" * count).html_safe
    end
  end
 

Then if I do this, what I want to happen is if resp is not null then it yields the block, otherwise it
yields two empty table cells.

<%= table_elements(resp,2) do %>
  <td><%= resp.remittance_id %></td>
  <td><%= resp.availability_date %></td>
<% end %>


 Since I have read alot of rails books and blogs and never seen anything quite this odd, I suspect someone will suggest an alternate way of doing this but at the moment I can't think of anything different. This helper almost works the way intended, but for some reason 3 extra ending tags </td> are getting thrown into the beginning of the page ..


Jedrin

unread,
Oct 8, 2015, 10:49:14 AM10/8/15
to Ruby on Rails: Talk

So this works perfectly but I am not sure why and I suspect I would not get any points for being elegant. If someone can comment on this or provide a better solution I would appreciate it


  def table_elements(qualifier, count)
    if qualifier
      yield
      return ""

Dave Aronson

unread,
Oct 8, 2015, 10:59:35 AM10/8/15
to rubyonrails-talk
On Thu, Oct 8, 2015 at 10:39 AM, Jedrin <jrub...@gmail.com> wrote:

> I have a helper like this:
>
> def table_elements(qualifier, count)
> if qualifier
> yield
> else
> return ("<td></td>" * count).html_safe
> end
> end

Try a NullObject. That is, supposing qualifier is of type Client,
have a class NullClient where remittance_id and availability_date are
nil. Make your data include NullClients instead of any nils. If I
remember rightly, a couple years ago Avdi Grimm put out a gem that
does a lot of the boilerplate in applying the Null Object pattern.

-Dave

--
Dave Aronson, consulting software developer of Codosaur.us,
PullRequestRoulette.com, Blog.Codosaur.us, and Dare2XL.com.

Jedrin

unread,
Oct 8, 2015, 11:18:10 AM10/8/15
to Ruby on Rails: Talk

Maybe I could do this .. good idea .. I've been doing too much JavaScript lately

class NullObject
  def self.method_missing(sym, *args, &block)
      return nil
    end
end

Reply all
Reply to author
Forward
0 new messages