Ruby on Rails Helpful Helpers: Content Tags

Another common thing I like to do is use a helper method to handle tricky tag-soupish markup. A client may have 1 URL, in which case I would like to simply display it, but if they have multiple URLs I’d like to put it in a list format. The only problem with using the content_tag function is that it ugly to do HTML building. (And sometimes you just don’t _need_ a builder…) This is just a simple wrapper for these cases.

  def content_tag_each(items)
    items.inject(''){ |output, item| output << yield(item) }
  end

Usage

# urls = (string) semi-colon seperated URL list since this is
# from a legacy system and doesn't really need normalization
def display_urls(urls)
  link_options = {:target => :blank}
  urls = urls.split(';')

  # handle single url
  return link_to(urls.first, urls.first, link_options) unless urls.size > 1

  # handle multiple urls
  content_tag(:ul) do
    content_tag_each(urls) do |url|
      content_tag(:li){ link_to(url, url, link_options) }
    end
  end
end

Nothing special really, but can come in handy for certain cases.



Comments

  1. Doug Johnston March 23rd

    Comment Arrow

    Thanks, this was super helpful!!


Add Yours

  • Author Avatar

    YOU


Comment Arrow



About Author

Rob Hurring

Ruby, Rails, PHP, bash... oh my!