重用ActiveAdmin组件

时间:2018-11-20 20:46:21

标签: ruby-on-rails activeadmin

我有很多模型,很多模型都需要相同的设置(动作按钮,成员动作,面板等)。我如何在许多地方重用代码并使代码保持DRY,而不是到处都复制/粘贴相同的代码块。

例如我在每个资源上都需要此代码:

member_action :purge_cache, method: :post do
    CacheManager.new(resource).purge_all
end

2 个答案:

答案 0 :(得分:1)

在ActiveAdmin :: Resource check how they are doing it中创建模块

答案 1 :(得分:0)

我找到了另一种方法:

创建<?php $ds = DIRECTORY_SEPARATOR; $storeFolder = 'images'; if (!empty($_FILES)) { $tempFile = $_FILES['file']['tmp_name']; $targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds; $file_name = substr(md5(rand(1, 213213212)), 1, 5) . "_" . str_replace(array('\'', '"', ' ', '`'), '_', $_FILES['file']['name']); $targetFile = $targetPath. $file_name; if(move_uploaded_file($tempFile,$targetFile)){ die( $_SERVER['HTTP_REFERER']. $storeFolder . "/" . $file_name ); }else{ die('Fail'); } } ?> plugins: [ 'advlist autolink lists link image imagetools charmap print preview anchor textcolor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table contextmenu paste code help wordcount' ], toolbar: 'insert | undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help', content_css: [ '//fonts.googleapis.com/css?family=Lato:300,300i,400,400i', '//www.tinymce.com/css/codepen.min.css'] });

/app/admin/concerns/shared_stuff.rb

只要您要执行相同的操作,就可以使用:

module SharedStuff
  def self.extended(base)
    base.instance_eval do
      member_action :purge_cache, method: :post do
        CacheManager.new(resource).purge_all
      end
    end
  end
end

您可以使用这种方式轻松添加面板,过滤器,批处理操作等...

贷方转到:http://tmichel.github.io/2015/02/22/sharing-code-between-activeadmin-resources/