A lot of Rails tag helpers (e.g. content_tag etc.) use a hash option parameter named class
to specify a HTML class.
content_tag(:div, content_tag(:p, "Hello world!"), class: "strong")
For new code I would like to use keyword arguments, but is that possible when one of them is a language keyword?
e.g. for a hypothetical link_tag
.
def link_tag(url, class: nil)
html = ''
html << '<a href="' << url << '"'
html << ' class="' << class << '"' if class
...
def link_tag(url, opts={})
html = ''
html << '<a href="' << url << '"'
html << ' class="' << opts[:class] << '"' if opts[:class]
...
Kind of. You have to avoid confusing the Ruby lexer by avoiding the literal keyword in your code, though. In Ruby 2.2+, you can get around it with binding.local_variable_get
:
def link_tag(url, class: nil)
format('<a href="%s" class="%s"></a>', url, binding.local_variable_get(:class))
end
link_tag("http://stackoverflow.com", class: "fancy")
# => "<a href=\"http://stackoverflow.com\" class=\"fancy\"></a>"
This isn't really a very clean way of doing things, though, and is likely to be confusing. I would just try to rename my arguments to not conflict with the language if I were to use keyword args, though (ie, css_class
or the conventional klass
, etc).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With