If you haven’t noticed yet that there is a good solution passing Rails variables from controllers to javascript I will be happy to make you fun with gon. In this post I will show how to use it with controller’s filters in a clean, dry and the best way. This approach will help you to avoid growing controllers in a big monsters.
Using filters in contollers
If you don’t know what is contoller filters and how use them, checkout oficial documentation. In our case we have to know that there are posibilities to apply filters for one action and this one form of using:
Using Gon
Say, we have to pass location model as a json object from server side to client side (from rails controller to javascript). With gon we can reduce it to:
Everything is ok, but if we have to pass a lot of variables to javascript we will get a fat controller. Also it’s not easy to test controllers. So my solution will be to use before_filter here. Here is a example of fat controller’s action:
This code looks too bad and I don’t know how you fill when you see it, but my brain explodes.
Useing Gon in a DRY way
So go down to business and make something with this peace of ugly code. Let’s create LocationGonFilter class and move it to app/filters folder. You should create this folder if you don’t have it.
After this we can refactor our controller:
Test for this filter will be look like this:
I’m using FactoryGirl here to create locations
PS. I believe that every class should be responsible for only one thing (this is a Single responsibility principle (SRP)). In my post I’ve explained how to achieve it for controller layer. Filters are separated layer and there we should filter parameters, controllers should inly listen requests, pass action to bottom layer (model) and then response on request, they should not contain complidated logic
gemrailsjavascriptAre you seeking assistance with Ruby on Rails development?