Sprockets is the thing behing Rails Asset Pipeline. It's a powerful asset processor with many already built-in goodies. It's the thing which takes your assets(be it sass, coffee, etc..) and does all the boring compiling, concatenating, minifiing and compressing. It's also designed to be easily extensible in case you need to integrate something Sprockets don't support out of the box.
Ok, so imagine you'v just discovered some new and shiny frontend thing you want to try. Let's say it's Elm. Now wouldn't it be nice if you could just drop Elm files in you
app/assets, let the Asset Pipeline handle the heavy lifting, and just focus on new realtime search in your side project(which is gonna be the next big thing)?
I know it would. And it doesn't take more than 10 minutes. Let's do it from top to bottom:
On the first line we tell Sprockets how to recognize Elm files - by theirs '.elm' file extension. On the second line we say what Sprockets should do with them - transform with our custom ElmTransformer processor.
The things which process various source files in Sprockets are called simply 'processors'. There are few types of them. The type we need now is 'transformer' - it takes source code in one language(Elm) and outputs it in another(JS).
Processor is anything which responds to `#call` method with one argument. Like this for Elm:
# lib/elm_transformer.rb require 'elm/compiler' class ElmTransformer def call(input) input_file = input[:filename] compiled_elm = Dir.chdir(Rails.root) do ::Elm::Compiler.compile(input_file) end compiled_elm end end
Now to test it in action, install new Elm package in you Rails root with `elm package install` and create following Elm file:
And lastly in some Rails view:
And this is it! This is all it takes to integrate completelly different language into Rails. Go visit the page and see yourself. Pretty cool for about 20 LOC isn't it?
I build this example app with which you can experiment if you want: https://github.com/Masa331/sprockets_plugin_example_app
Hi, i'm Přemysl Donát and this is my place.
This is my picture:
I'm a web developer. I like Ruby the most but i'm fine with other technology also. After all, it's just technology.
One of my side projects is DameData.cz. It's a web app which helps you to easily connect your business with accounting(czech market only right now). Check it out:
Have a good one, PřemekFollow @DonatP Follow @Masa331