1

Take a look at these two lines:

   <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
   <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload', :defer => "defer" %>

That is generated by default in a new rails project, except for the :defer part, which I included to defer my scripts based on the method advised by this answer.

Note that media is neither a symbol or a string, while :defer is a symbol and 'data-turbolinks-track' is a string. I don't even know what terminology to use here so I'm calling them "include attributes," since they are the names of attributes on an include in my application.html.erb.

Why are there different types here? Which is suggested? Why do all three work? I find this frustrating.

temporary_user_name
  • 35,956
  • 47
  • 141
  • 220

1 Answers1

2

Everything after application is actually a hash with symbol keys. In general,

{foo: 'bar'}

is equivalent to

{:foo => 'bar'}

When you have a string that has spaces, hyphens, etc., you need to enclose it in quotes before adding the colon; that's what's going on with 'data-turbolinks-track':.

Finally, when passing arguments to a method, you can leave out the curly braces on the outside of the hash as long as it's unambiguous. This is often called a bare hash.

So, your calls are actually equivalent to:

<%= stylesheet_link_tag    'application', {:media => 'all', :'data-turbolinks-track' => 'reload'} %>
<%= javascript_include_tag 'application', {:'data-turbolinks-track' => 'reload', :defer => "defer"} %>

As for which syntax to use, it's mostly a question of style and readability unless you're using older versions of Ruby (before Ruby 1.9, the "rocket" syntax using => was the only option).

Max
  • 1,817
  • 1
  • 10
  • 13