ruby-on-railsactiveadminpaper-trail-gem

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.


Solution

  • 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