Asset_path method in javascript application rails code

    Rails-rich client applications use client-side templates. If these templates are processed using the Asset Pipeline, then the question arises of 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 right way is to wrap JavaScript in a preprocessor Erbwhere the desired helper will be available. <%= asset_path(path/to/template.html) %>

    We will implement a more beautiful solution.

    Let us have some application where templates are used on the client side. The preprocessor for templates is Slim [ 1 ]. We will not focus on the way the source code is organized in the project. Let all our patterns lie in app/assets/webapp/. Let's configure our application so that it picks up templates *.html.slimfrom our templates directory:
    # 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 template app/assets/webapp/rubrics/edit.html.slimand want to access it from JavaScript. /assets/rubrics/edit.htmlWe cannot contact the address , since there will not be such a file in the production environment, but there will be something /assets/rubrics/edit-5eb3bb250d5300736006c8944e436e3f.html. The correspondence table between the logical path rubrics/edit.htmland the full path lies in the manifest file, which is generated automatically. But using it is not always justified; at least it contains a lot of extra data.

    Gem js_assetssolves the problem of compiling a correspondence table for files matching a specific mask.

    After installing the gem, connect the JavaScript helper:
    // app/assets/javascripts/application.js
    //= require app_assets

    The correspondence table will be stored in a variable window.project_assets. The helper method asset_pathtakes as an argument the logical path to the required file and returns the path relative to 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

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

    You can expand them, for example, using initializers.

    The source code for gem can be found on github .

    Also popular now: