Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to add shared view files in Rails 5?

I am using Rails 5 and I want to use shared files in my project. I have searched the web about this, and I got some results as follow:

For Rails 3

app/views/shared

For Rails 4

app/views/application

but there was nothing for Rails 5.

I am talking about the standard; is there any specific location to add common view files in Rails 5, just as we do in other frameworks? Like in Laravel there is a layout folder?

like image 371
Amrinder Singh Avatar asked Dec 24 '22 03:12

Amrinder Singh


1 Answers

All the people telling you that there is no "standard location" for common view files are correct. However, if you want to ask Rails where it would go looking for a partial file if you attempted to render one on the view, just take any view file you have and render a partial you know doesn't exist.

If you have, say, a UsersController with a view structure that looks something like app/view/users, and you add the following on any view there:

<%= render 'foo' %>

You'll likely get an error that says something like:

Missing partial users/_foo, application/_foo

That means that whenever you attempt to render a partial by just it's name without any path information, Rails will look for it

  • first under the view directory for the current controller, in this case users
  • then under the application directory

So, I guess then you could say that the "default location" in Rails for common view files is under the application directory.

It's possible to add to this in order to create your app's own "standard location" for common view files by overriding the ActionView::ViewPaths.local_prefixes private class method that gets mixed in to every controller in Rails:

class ApplicationController < ActionController::Base
  def self.local_prefixes
    ['shared', controller_path]
  end
  private_class_method :local_prefixes
end

class UsersController < ApplicationController
  def self.local_prefixes
    [controller_path]
  end
  private_class_method :local_prefixes
end

Now, your error will say something like:

Missing partial users/_foo, shared/_foo, application/_foo

which shows that Rails will check the shared directory for partials as well before it goes looking in the application directory.

Note that this method override should happen in both the controllers, otherwise the local_prefixes in UsersController get inherited from ApplicationController and you end up with duplicated lookup paths that look like:

shared/_foo, users/_foo, shared/_foo, application/_foo

If all this is too much effort/too weird, as other people have pointed out, you can always just specify your shared partial directory manually when you render a partial:

<%= render 'shared/foo' %>
like image 90
Paul Fioravanti Avatar answered Jan 09 '23 11:01

Paul Fioravanti