Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a keyword argument named `class` or other reserved name in Ruby?

Tags:

ruby

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]
  ...
like image 594
Fire Lancer Avatar asked Dec 10 '22 10:12

Fire Lancer


1 Answers

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).

like image 195
Chris Heald Avatar answered Jan 05 '23 01:01

Chris Heald