📜 ⬆️ ⬇️

Structuring JS Assets in Rails 3.1 (Styx)

The asset mechanism in 3.1 greatly simplified the life of large projects, but at the same time made it a bit more difficult for small ones. When using built-in generators, rails still create a separate file for each controller, only now the contents of these files appear by default on absolutely all pages. If in the case of SCSS this only helps, imposing the correct structuring, then what to do with JS?

If the project is big and you use some client framework like Backbone for massive JS, great! It will load better and decide where and how it should work. But what if you only need to connect a small amount of code for specific pages? That is, not even controller'ov, but rather action'ov. And it is desirable that when such slices become more than 5, the code does not turn into spaghetti. A small Styx gem can help with this.

Styx is able not only to call specific code for a specific action, but also to pass data to it from Ruby. Preparations:

# Gemfile gem 'styx' # app/controllers/application_controller.rb    controller class ApplicationController include Styx::Initializer end # app/views/application.html.erb <%= javascript_include_tag "application" %> <%= styx_initialize %> <%= csrf_meta_tags %> 

')
If we have a FoosController controller that we created using `rails g foos', then through its efforts we also have not only app / controllers / foos_controller.rb, but also app / assets / javascripts / foos.js.coffee. Here's what the last one should look like:

 #        Styx.Initializers. @Styx.Initializers.Foos = initialize: -> console.log '        action  foos     <head>' index: (data) -> console.log '       /foos/     <head>' show: (data) -> $ -> console.log '    (  jQuery)       /foos/... (. jQuery.ready())' 


Note that all methods (except general initialize) take the data parameter. By default, this is an empty {} object, but it can be easily refilled from the side of the cut both directly in the controller and in view:

 # app/controllers/foos_controller.rb class ApplicationController def index styx_initialize_with :foo => 'bar', :and => {:habrahabr => 'rockz!'} end end 


 # app/views/foos/index.html.erb <%- styx_initialize_with :something => 'very important' %> 


Now we get in data:

 {"foo": "bar", "and": {"habrahabar": "rocks!"}, "something": "very important"} 


That's all it takes to call our code. Due to the fact that JS is collected in one file and is connected entirely, you can easily describe your repeating code in classes (namely classes, thanks to Coffee) and call them on the necessary pages using Initializer. And as a nice bonus - no more dumps ".to_json" for transferring data to JS in your views :).

Source: https://habr.com/ru/post/135850/


All Articles