davideghz
davideghz

Reputation: 3685

Rails - ActiveAdmin and Papertrail - a DRY approach

I have lot of Models where I use PaperTrail, like:

class User < ActiveRecord::Base
  has_paper_trail
end

In the ActiveAdmin model's file I have:

ActiveAdmin.register User do

  ...

  # versioning part
  action_item :history, only: :show do
    link_to('History', history_backend_user_path(user), method: :get)
  end

  sidebar :versionate, :partial => "layouts/version", :only => :show

  member_action :history do
    @user = User.find(params[:id])
    @versions = @user.versions.reorder(created_at: :desc)
    render "layouts/history"
  end
end

I have to repeat this lines for every model and I'm wondering how I could dry it up.

Upvotes: 3

Views: 2155

Answers (2)

davideghz
davideghz

Reputation: 3685

I finally ended up with the following solution which is working (note also that all the references to User resource have been generalized):

# app/admin-shared/active_admin_loggable.rb

module ActiveAdminLoggable
  def self.extended(base)
    base.instance_eval do
      action_item :history, only: :show do
        link_to('History',
                eval("history_backend_#{resource.class.to_s.downcase}_path(#{resource.class.to_s.downcase})"),
                method: :get
        )
      end

      sidebar :versionate, :partial => "layouts/version", :only => :show

      member_action :history do
        @this_resource = eval("resource.class").find(params[:id])
        @versions = @this_resource.versions.reorder(created_at: :desc)
        render "layouts/history"
      end
    end
  end
end

and:

# app/admin/user.rb
ActiveAdmin.register User do
  extend ActiveAdminLoggable
  ...
end

Upvotes: 2

Tom Aranda
Tom Aranda

Reputation: 6026

Try separating the common code into a concern. You can then use ActiveAdmin's include method to incorporate the common code into your resources.

Here is the module which should contain your common code:

# app/admin/concerns/versionable.rb
module Versionable
  def self.included(dsl)
    dsl.action_item :history, only: :show do
      link_to 'History', dsl.history_backend_user_path(user), method: :get
    end

    dsl.sidebar :versionate, :partial => "layouts/version", :only => :show

    dsl.member_action :history do
      @user = User.find(params[:id])
      @versions = @user.versions.reorder(created_at: :desc)
      render "layouts/history"
    end
  end
end

You can then include this module in your ActiveAdmin resources. For example:

# app/admin/user.rb
ActiveAdmin.register User do
  include Versionable
  ...
end

This is based on this Stack Overflow post. It has not been tested.

Upvotes: 0

Related Questions