All Case Studies Design Development Interviews Our Way Project Management

How to Use Rails Assets Directly in Your JS Files with RWR View Helpers

Here at Netguru, we love working with both Rails and React on our tech stack, and, lately, we’ve found ourselves using them more and more. But there has always been a problem with using image paths (rails adding digest hashes) in our React components - we had to pass it as a prop from views to redux containers and from there to our dumb components. That involves a lot of redundant steps, making it more likely that something will go wrong; this is why we came up with rwr-view-helpers, which makes it possible for developers to access Rails assets directly in javascript.


1. How Does It Work?

When we start our Rails server, the first request will generate a cache for rwr-view_helpers in the form of json & js files with hash mapping assets’ urls to urls with a generated digest-hash.

The .gif, .jpg, .png file extensions are supported by default. More can  be added easily according to the user’s needs.


2. How to Install It?

The installation of helpers is really straightforward, all you have to do is:

  • install it with npm:
$ npm install --save rwr-view-helpers

  • add the gem to your Gemfile:
$ gem 'rwr-view_helpers'

  • require the js file in application.js:
//=require rwr_view_helpers`


3. How to Use It?

Using helpers is extremely easy - they’re simply exported as a function from our node module:


The only thing you need to remember at this point is to generate a new cache by running the rake task each time you add new assets to your project and want to use them in your javascript files.

$ rake tmp:clear


4. Contributing

While, at the moment, there is only imagePath helper - we are looking forward to adding more. If you are missing something you really need, let us know or, even better, open PR!


5. Future Updates

We’re currently working on automating the cache generation process with assets watcher, so make sure to star our repo and stay tuned for amazing updates in the near future.

Follow Netguru
Join our Newsletter

Read also
Need a successful project?
Estimate project or contact us
How to Use Rails Assets Directly in Your JS Files with RWR View Helpers