From 6e5a2b6bb0e57f3807b4b80bdf2d7a08d19f471b Mon Sep 17 00:00:00 2001 From: Charles Maresh Date: Mon, 18 Nov 2013 08:40:07 -0600 Subject: [PATCH] Add `roots_collection` option Allow users to define custom logic to find the roots of the tree to be rendered, while staying backward compatible. Users may now do: ActiveAdmin.register TreeNode do sortable tree: true, roots_collection: proc { current_user.tree_nodes.roots } end --- lib/active_admin/views/index_as_sortable.rb | 32 +++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/lib/active_admin/views/index_as_sortable.rb b/lib/active_admin/views/index_as_sortable.rb index 8b7d7f6..5d16ed4 100644 --- a/lib/active_admin/views/index_as_sortable.rb +++ b/lib/active_admin/views/index_as_sortable.rb @@ -6,7 +6,7 @@ class IndexAsSortable < ActiveAdmin::Component def build(page_presenter, collection) @page_presenter = page_presenter @collection = if tree? - resource_class.send(options[:roots_method]) + roots else collection end @@ -29,6 +29,34 @@ def options active_admin_config.dsl.sortable_options end + def roots + roots_collection || default_roots_collection + end + + # Find the roots by calling the roots method directly on the resource. + # This effectively performs: + # + # TreeNode.roots # => [#, ... ] + # + # Returns collection of roots. + def default_roots_collection + resource_class.send(options[:roots_method]) + end + + # Use user-defined logic to find the root nodes. This executes a callable + # object within the context of the resource's controller. + # + # Example + # + # options[:roots_collection] = proc { current_user.tree_nodes.roots } + # + # Returns collection of roots. + def roots_collection + if (callable = options[:roots_collection]) + controller.instance_exec(&callable) + end + end + def tree? !!options[:tree] end @@ -80,7 +108,7 @@ def build_nested_item(item) div :class => "cell left" do resource_selection_cell(item) if active_admin_config.batch_actions.any? end - + span :class => :disclose do span end if options[:collapsible]