wadeva
Last Updated: February 25, 2016
·
3.201K
· macfanatic

Extending ActiveAdmin DSL

ActiveAdmin is a great Rails 3 gem allowing you to quickly prototype "admin" web applications, and then build upon the foundation with customizations to turn your basic application into something unique.

The gem offers a gorgeous DSL for customizing behavior, and this post shows you how to add more DSL magic to your application logic, or as posted below, via a gem.

There are several tutorials on creating Rails 3 gems via bundler, so follow those. I'm naming my gem "activeadminactsaslist", full code available here on github.

In the gem initializer, use the following code to require our seperate module that we'll inject into the ActiveAdmin DSL class itself.

require 'active_admin/acts_as_list/dsl'

::ActiveAdmin::DSL.send(:include, ActiveAdmin::ActsAsList::DSL)

Then, in the file defining the DSL extensions, we use the following:

module ActiveAdmin
  module ActsAsList
    module DSL

      # Call this inside your resource definition to add the needed member actions
      # for your sortable resource.
      #
      # Example:
      #
      # #app/admin/players.rb
      #
      #  ActiveAdmin.register Player do
      #    # Sort players by position
      #    config.sort_order = 'position'
      #   
      #    # Add member actions for positioning.
      #    sortable_member_actions
      #  end
      def sortable_member_actions
       member_action :move_to_top do
          if resource.first?
            redirect_to :back, :notice => I18n.t('acts_as_list.illegal_move_to_top', :resource => resource_class.to_s.camelize.constantize.model_name.human ) 
            return
          end  

          resource.move_to_top
          redirect_to :back, :notice => I18n.t('acts_as_list.moved_to_top', :resource => resource_class.to_s.camelize.constantize.model_name.human )
        end
      end

    end
  end
end

Overall, we're not doing anything special with ActiveAdmin, this is basic Ruby module mixin behavior. However, the key is including our module in the ActiveAdmin::DSL class

1 Response
Add your response

15251

Thanks for sharing

over 1 year ago ·