📜 ⬆️ ⬇️

The asset_path method in javascript application rails code

Rich client-side Rails applications use client-side templates. If these templates are processed using Asset Pipeline, then the question arises about how to access them. In a production environment, the path to the file is made up of its name and md5 hash. One of the options to get the desired path is to wrap the JavaScript in the Erb preprocessor, where the necessary helper <%= asset_path(path/to/template.html) %> will be available

We will introduce a more beautiful solution.

Let we have some application where client side templates are used. Preprocessor for templates we will select Slim [ 1 ]. We will not focus on the way the source code is organized in the project. Let all our templates lie in app/assets/webapp/ . Let us configure our application so that it picks up templates *.html.slim from our directory with templates:
 # config/application.rb config.assets.paths << Rails.root.join('app', 'assets', 'webapp') # config/initizlizers/assets_engine.rb Rails.application.assets.register_engine('.slim', Slim::Template) # config/environments/production.rb config.assets.precompile += ['*.html'] 


We have created a certain app/assets/webapp/rubrics/edit.html.slim and want to access it from JavaScript. We cannot go to /assets/rubrics/edit.html , because there will be no such file in the production environment, but something will be /assets/rubrics/edit-5eb3bb250d5300736006c8944e436e3f.html . The correspondence table between the logical path rubrics/edit.html and the full rubrics/edit.html lies in the manifest file that is automatically generated. But using it is not always justified, it at least contains a lot of redundant data.
')
Gem js_assets solves the problem of creating a matching table for files that fall under a particular mask.

After installing the gem, let's enable the JavaScript helper:
 // app/assets/javascripts/application.js //= require app_assets 

The correspondence table will be stored in the variable window.project_assets . The helper asset_path method takes as an argument the logical path to the required file and returns the relative path from the root, taking into account the environment.
 var path = asset_path('rubrics/edit.html') // the function will return for development: // /assets/rubrics/edit.html // and for production // /assets/rubrics/edit-5eb3bb250d5300736006c8944e436e3f.html 


Managing the list of available files (taking into account the asset pipeline processing) for the helper is done through filters. Their default values ​​are:
 JsAssets::List.exclude = ["application.js"] JsAssets::List.allow = ["*.html"] 

You can expand them for example using initializers .

The gem source code can be found on github .

Source: https://habr.com/ru/post/194968/


All Articles