Rubytastic
Rubytastic

Reputation: 15501

secure a specific /assets file from direct access in routes or else somehow?

secure a specific /assets file from direct access in routes or else somehow?

I have inside my assets like fronted.css and backend.css This backend css file I would to disable direct access from URL so It can only be loaded from inside my backend_controller.rb.

Is this possible somehow?

Upvotes: 0

Views: 338

Answers (1)

jbmeerkat
jbmeerkat

Reputation: 335

In production Rails don`t control assets, this is work for webserver. You can only hide them by excluding from public part of site.

You can use different layouts for frontend and backend or inject some data for custom actions.

Layouts way:

  1. In backend_controller.rb:

    class BackendController...
      layout 'backend' #you can use :only or :except parameter if you need
      ...
    end
    
  2. In /your_app/app/assets/stylesheets create backend.css and folder 'backend', move all your backend stylesheets in 'backend' folder and in backend.css insert this:

    /*
     *= require_self
     *= require_tree ./backend
    */
    
  3. Create in /your_app/app/views/layouts file backend.html.erb. This is your backend layout. Insert there <%= stylesheet_link_tag "backend" %>

  4. Dont forget to remove from /your_app/app/assets/application.css line *= require_tree .(this directive recursive including all files in /your_app/app/assets/stylesheets and your backend.css too). If you need to require some files or directories use *= require file_name_without_extension or *= require_tree ./directory_name

Injecting way:

  1. In /your_app/app/views/layouts/application.html.erb

    <!DOCTYPE html>
    <html>
      <head>
        <%= stylesheet_link_tag    "application", :media => "all" %>
        ...
        <%= yield :my_custom_css %>
      </head>
      ...
    
  2. In any file you need your custom stylesheet(e.g. /your_app/app/views/categories/new.html.erb):

    <% content_for :my_custom_css do %>
      <%= stylesheet_link_tag 'backend' %>
    <% end %>
    
  3. And remove *= require_tree . from /your_app/app/assets/application.css or your custom css file will be included in application layout

content_for documentation

Upvotes: 2

Related Questions