Skip to content

Instantly share code, notes, and snippets.

@rwilcox
Created September 21, 2011 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwilcox/1233059 to your computer and use it in GitHub Desktop.
Save rwilcox/1233059 to your computer and use it in GitHub Desktop.
presenter_pattern_gone_wrong?
# If the item has one comment, show it, else show the last comment and allow the user to expand
# (yes, a slightly contrived example)
def primary_comment
if self.comemnts.count > 1
"<details class='primary_comment details'><summary><h3>" + self.comments.last.text + " (and #{self.comments.count - 1} others)"
"<ul>"
self.comments.each[0...-1] do |comment|
"<li>" + comment.text + "</li>"
end
else
"<span class='primary_url'>" + self.comments.last.text + "</span>"
end
end
@saturnflyer
Copy link

You can write more methods to simplify it while opening up the possibility to reuse them elsewhere.

def primary_comment
  if comments.count < 2
    main_comment
  else
    comments_detail_list
  end
end

def main_comment
  "<span class='primary_url'>" + self.comments.last.text + "</span>"
end

def comments_detail_list
  output = %{<details class='primary_url details'><summary>#{header_comment}</summary><ul>}
  each_comment do |comment|
    output << simple_comment_item(comment)
  end
  output + "</ul></details>"
end

def header_comment
  %{<h3>#{comments.last.text} (and #{comments.count} others)</h3>}
end

def simple_comment_item(comment)
  "<li>"+comment.text+"</li>"
end

def each_comment(&block)
  comments.each do |comment|
    yield comment
  end
end

@rwilcox
Copy link
Author

rwilcox commented Sep 21, 2011

Very interesting. Thank you - I do like the idea of making the methods smaller. Still with the string concatenation, but that might be a good thing (Trying to shove ERB in the presenter might actually be a bad thing).

@rwilcox
Copy link
Author

rwilcox commented Sep 22, 2011

... and I figured out why I didn't like the string concatenation, Jim (@saturnflyer): it works great on Rails 2.x project. However, as soon as you're on a Rails 3 project you have to throw all kinds of .html_safe calls everywhere and it gets impossible to use (too much thinking!).

I'll have to do more noodling.

@rwilcox
Copy link
Author

rwilcox commented Sep 22, 2011

... which I think I figured out how to make elegant. I'll write a blog post on same in the morning.

@rwilcox
Copy link
Author

rwilcox commented Sep 23, 2011

The cunning conclusion to this story can be found on my blog: http://rwilcox.tumblr.com/post/10546160404/presenter-pattern-rails-3-and-html-safe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment