Active Admin custom JavaScript for diverse pages


Active Admin provides fancy language to implement admin interface fast. But sometimes it would be very helpful to have an ability to add some custom JavaScript to diverse pages and actions.

For example, we have file articles.rb in app/admin folder. And we want to add some custom JS only to edit action, for example. Of course, we can manipulate JavaScript adding one in config/active_admin.rb:

  config.register_javascript 'custom_javascript.js'

But it would be awesome to add per page javascript for separate action (‘edit’ as you remember). During my research and googling I found one hack to implement such functionality:

Put layout.rb into app/admin folder with this content:

  module ActiveAdmin::Views::Pages::BaseExtension
    def add_classes_to_body
      super
      @body.set_attribute "data-controller", params[:controller].gsub(/^admin\//, '')
      @body.set_attribute "data-action",     params[:action]
    end
  end
  class ActiveAdmin::Views::Pages::Base
    # mixes in the module directly below the class
    prepend ActiveAdmin::Views::Pages::BaseExtension
  end

Add to app/assets/javascripts/active_admin.js.coffee

  ActiveAdmin = {
    dashboard: {},
    articles: {}
  }

  ActiveAdmin.articles.edit = () ->
    console.log('articles#edit')

  $(() ->
    controller = $('body').data('controller')
    action = $('body').data('action')
    ActiveAdmin[controller][action]() if ActiveAdmin[controller]? && ActiveAdmin[controller][action]?
  )

Well, that’s it.

Related Posts

Golang and OpenAPI(Swagger). How to create documentation for your REST API services

Game of Code Review. How code review can improve the health of your team

The easiest way to localize SPA application using polyglot.js

The simplest way to localize your modern single page application

Presenters in javascript

An article describing using presenters in your javascript code

Deploying rails apps, part 3. Configuring capistrano, nginx with puma

The third article of deployment series. Configuring capistrano, nginx with puma

Deploying rails apps, part 2. Setting up the necessary software

The second article of deployment series. Setting up the necessary software.

Deploying rails apps, part 1. Bootstrap the server

The first article of deployment series. Bootstrap the server.