Skip to content

Instantly share code, notes, and snippets.

@jmuheim
Created September 14, 2012 11:52
Show Gist options
  • Save jmuheim/3721506 to your computer and use it in GitHub Desktop.
Save jmuheim/3721506 to your computer and use it in GitHub Desktop.
Rails signatures ...
# Creates a Twitter Bootstrap nav item.
#
# @see http://twitter.github.com/bootstrap/components.html#navs
#
# @param [String optional] caption The caption of the item, optional if a block is passed
# @param [String optional] url The URL of the item
# @param [Hash] options
# @option options [Boolean] :brand (false) Set to true to define this item as the brand (this should be called directly on the `navbar` element itself as it also omits the surrounding `li` element)
# @option options [Boolean] :icon (nil) Pass the name of an icon (without the prefix `icon-`) to have an icon displayed to the left of the caption; see [available icons](http://twitter.github.com/bootstrap/base-css.html#icons)
# @return [String] HTML code
def item(*args, &block)
options = args.extract_options!
options.reverse_update({
brand: false,
icon: false,
})
caption, url = if block_given?
[capture(&block), args[0]]
else
[args[0], args[1]]
end
a_classes = []
a_classes << 'brand' if options[:brand]
icon_content = (options[:icon] ? content_tag(:i, '&nbsp;'.html_safe, class: "icon-#{options[:icon]}") : '').html_safe
content = link_to(url, class: a_classes.join(' ')) do
icon_content + caption
end
options[:brand] ? content : content_tag(:li, content)
end
@tokland
Copy link

tokland commented Sep 14, 2012

Hi again (coming from http://stackoverflow.com/questions/12423224/how-to-merge-some-keys-into-args-and-then-call-another-method-with-those-args/12423413#12423413)

Of, that's what Rails does so I guess is a valid approach (though personally I don't like it). An alternative is using two different methods if it's to be used with a block. Yeah, not a wonderful alternative, but more cleaner on the signatures side (and the code will be cleaner, less conditionals).

Minor suggestion on the functional side:

a_classes = ['brand' if options[:brand]].compact

@tokland
Copy link

tokland commented Sep 14, 2012

I thought comments were editable... well, anyway, I meant:

a_classes = [('brand' if options[:brand])].compact

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