Skip to content

Instantly share code, notes, and snippets.

@rpunkfu
Last active September 9, 2016 12:09
Show Gist options
  • Select an option

  • Save rpunkfu/cfb1b2140e1b7e3242991f052b663fd0 to your computer and use it in GitHub Desktop.

Select an option

Save rpunkfu/cfb1b2140e1b7e3242991f052b663fd0 to your computer and use it in GitHub Desktop.

Table of Contents

  1. How does it work?
  2. How to install it?
  3. How to use it?
  4. Contributing
  5. Future updates

———————————————————————————————————————————————————————

Using Rails assets directly in your javascript files with RWR View Helpers.

Here at Netguru we love working with both Rails + React on our tech stack and lately we find ourselves using them more & more. But there was always 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. There’s a lot of redundant steps there, making it more likely to break things, that’s 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, first request will generate cache for rwr-view_helpers in form of json & js files with hash mapping assets urls to urls with generated digest-hash.

File extensions supported by default are: ‘.gif’, ‘.jpg’, ‘.png’. Those can easily be extended to more, according to user’s needs.

2. How to install it?

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

  • install it with npm:
$ npm install --save rwr-view-helpers
  • add gem to your Gemfile:
$ gem 'rwr-view_helpers'
  • require js file in application.js:
//=require rwr_view_helpers`

3. How to use it?

Usage of helpers is extremely easy, it’s just exported as a function from our node module:

import React from 'react';
import { imagePath } from 'rwr-view-helpers';
import { facebookIcon } from 'constants/icon-urls';

export default ({ alt }) => (
  <img alt={alt} src={imagePath(facebookIcon)} />
);

Only thing you have to remember about at the moment is to generate new cache, by running rake task each time you add new assets to your project and you want to use them in your javascript files.

$ rake tmp:clear

4. Contributing

While for now there is only imagePath helper, we are looking forward for adding more of them. If you are missing something very bad, let us know or even better open PR!

5. Future updates

Right now we’re working on automatisation of cache generation process with assets watcher, so make sure to star our repo and stay tuned for those amazing updates in near future.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment