repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/resource/comments_spec.rb | spec/unit/resource/comments_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe "ActiveAdmin Comments", type: :controller do
before do
load_resources { ActiveAdmin.register ActiveAdmin::Comment, as: "Comment" }
@controller = Admin::CommentsController.new
end
describe "#destroy" do
let(:user) { User.create! }
let(:comment) { ActiveAdmin::Comment.create!(body: "body", namespace: :admin, resource: user, author: user) }
context "success" do
it "deletes comments and redirects to root fallback" do
delete :destroy, params: { id: comment.id }
expect(response).to redirect_to admin_root_url
end
it "deletes comments and redirects back" do
request.env["HTTP_REFERER"] = "/admin/users/1"
delete :destroy, params: { id: comment.id }
expect(response).to redirect_to "/admin/users/1"
end
end
context "failure" do
it "does not delete comment on error and redirects to root fallback" do
expect(@controller).to receive(:destroy_resource) do |comment|
comment.errors.add(:body, :invalid)
end
delete :destroy, params: { id: comment.id }
expect(response).to redirect_to admin_root_url
end
it "does not delete comment on error and redirects back" do
request.env["HTTP_REFERER"] = "/admin/users/1"
expect(@controller).to receive(:destroy_resource) do |comment|
comment.errors.add(:body, :invalid)
end
delete :destroy, params: { id: comment.id }
expect(response).to redirect_to "/admin/users/1"
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/resource/pagination_spec.rb | spec/unit/resource/pagination_spec.rb | # frozen_string_literal: true
require "rails_helper"
module ActiveAdmin
RSpec.describe Resource, "Pagination" do
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { Namespace.new(application, :admin) }
def config(options = {})
@config ||= Resource.new(namespace, Category, options)
end
describe "#paginate" do
it "should default to true" do
expect(config.paginate).to eq true
end
it "should be settable to false" do
config.paginate = false
expect(config.paginate).to eq false
end
end
describe "#per_page" do
it "should default to namespace.default_per_page" do
expect(namespace).to receive(:default_per_page).and_return(5)
expect(config.per_page).to eq 5
end
it "should be settable" do
config.per_page = 5
expect(config.per_page).to eq 5
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/resource/includes_spec.rb | spec/unit/resource/includes_spec.rb | # frozen_string_literal: true
require "rails_helper"
module ActiveAdmin
RSpec.describe Resource, "Includes" do
describe "#includes" do
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { ActiveAdmin::Namespace.new application, :admin }
let(:resource_config) { ActiveAdmin::Resource.new namespace, Post }
let(:dsl) { ActiveAdmin::ResourceDSL.new(resource_config) }
it "should register the includes in the config" do
dsl.run_registration_block do
includes :taggings, :author
end
expect(resource_config.includes.size).to eq(2)
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/resource/page_presenters_spec.rb | spec/unit/resource/page_presenters_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Resource::PagePresenters do
let(:namespace) { ActiveAdmin::Namespace.new(ActiveAdmin::Application.new, :admin) }
let(:resource) { namespace.register(Post) }
it "should have an empty set of configs on initialize" do
expect(resource.page_presenters).to eq({})
end
it "should add a show page presenter" do
page_presenter = ActiveAdmin::PagePresenter.new
resource.set_page_presenter(:show, page_presenter)
expect(resource.page_presenters[:show]).to eq page_presenter
end
it "should add an index page presenter" do
page_presenter = ActiveAdmin::PagePresenter.new({ as: :table })
resource.set_page_presenter(:index, page_presenter)
expect(resource.page_presenters[:index].default).to eq page_presenter
end
describe "#get_page_presenter" do
it "should return a page config when set" do
page_presenter = ActiveAdmin::PagePresenter.new
resource.set_page_presenter(:index, page_presenter)
expect(resource.get_page_presenter(:index)).to eq page_presenter
end
it "should return a specific index page config when set" do
page_presenter = ActiveAdmin::PagePresenter.new
resource.set_page_presenter(:index, page_presenter)
expect(resource.get_page_presenter(:index, "table")).to eq page_presenter
end
it "should return nil when no page config set" do
expect(resource.get_page_presenter(:index)).to eq nil
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/resource/sidebars_spec.rb | spec/unit/resource/sidebars_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Resource::Sidebars do
let(:resource) do
namespace = ActiveAdmin::Namespace.new(ActiveAdmin::Application.new, :admin)
namespace.register(Post)
end
let(:sidebar) { ActiveAdmin::SidebarSection.new(:help) }
describe "adding a new sidebar section" do
before do
resource.clear_sidebar_sections!
resource.sidebar_sections << sidebar
end
it "should add a sidebar section" do
expect(resource.sidebar_sections.size).to eq(1)
end
end
describe "retrieving sections for a controller action" do
let(:only_index) { ActiveAdmin::SidebarSection.new(:help, only: :index) }
let(:only_show) { ActiveAdmin::SidebarSection.new(:help, only: :show) }
before do
resource.clear_sidebar_sections!
resource.sidebar_sections << only_index
resource.sidebar_sections << only_show
end
it "should only return the relevant action items" do
expect(resource.sidebar_sections.size).to eq(2)
expect(resource.sidebar_sections_for("index")).to eq [only_index]
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/resource/routes_spec.rb | spec/unit/resource/routes_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Resource::Routes do
let(:application) { ActiveAdmin.application }
let(:namespace) { application.namespace(:admin) }
context "when in the admin namespace" do
let(:config) { namespace.resource_for("Category") }
around do |example|
with_resources_during(example) { ActiveAdmin.register Category }
end
let(:category) { Category.new { |c| c.id = 123 } }
it "should return the route prefix" do
expect(config.route_prefix).to eq "admin"
end
it "should return the route collection path" do
expect(config.route_collection_path).to eq "/admin/categories"
end
it "should return the route instance path" do
expect(config.route_instance_path(category)).to eq "/admin/categories/123"
end
end
context "when in the root namespace" do
let!(:config) { ActiveAdmin.register Category, namespace: false }
around do |example|
with_resources_during(example) { config }
end
after do
application.namespace(:root).unload!
application.namespaces.instance_variable_get(:@namespaces).delete(:root)
end
it "should have a nil route_prefix" do
expect(config.route_prefix).to eq nil
end
it "should generate a correct route" do
expect(config.route_collection_path).to eq "/categories"
end
end
context "when registering a plural resource" do
class ::News; def self.has_many(*); end end
let!(:config) { ActiveAdmin.register News }
around do |example|
with_resources_during(example) { config }
end
it "should return the plural route with _index" do
expect(config.route_collection_path).to eq "/admin/news"
end
end
context "when the resource belongs to another resource" do
let(:config) { namespace.resource_for("Post") }
let :post do
Post.new do |p|
p.id = 3
p.category = Category.new { |c| c.id = 1 }
end
end
before do
load_resources do
ActiveAdmin.register Category
ActiveAdmin.register(Post) do
belongs_to :category
member_action :foo
end
end
end
it "should nest the collection path" do
expect(config.route_collection_path(category_id: 1)).to eq "/admin/categories/1/posts"
end
it "should nest the instance path" do
expect(config.route_instance_path(post)).to eq "/admin/categories/1/posts/3"
end
it "should nest the member action path" do
expect(config.route_member_action_path(:foo, post)).to eq "/admin/categories/1/posts/3/foo"
end
end
context "for batch_action handler" do
before do
load_resources { config.batch_actions = true }
end
context "when register a singular resource" do
let :config do
ActiveAdmin.register Category
ActiveAdmin.register Post do
belongs_to :category
end
end
it "should include :scope and :q params" do
params = ActionController::Parameters.new(category_id: 1, q: { name_eq: "Any" }, scope: :all)
additional_params = { locale: "en" }
batch_action_path = "/admin/categories/1/posts/batch_action?locale=en&q%5Bname_eq%5D=Any&scope=all"
expect(config.route_batch_action_path(params, additional_params)).to eq batch_action_path
end
end
context "when registering a plural resource" do
class ::News; def self.has_many(*); end end
let(:config) { ActiveAdmin.register News }
it "should return the plural batch action route with _index and given params" do
params = ActionController::Parameters.new(q: { name_eq: "Any" }, scope: :all)
additional_params = { locale: "en" }
batch_action_path = "/admin/news/batch_action?locale=en&q%5Bname_eq%5D=Any&scope=all"
expect(config.route_batch_action_path(params, additional_params)).to eq batch_action_path
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/resource/attributes_spec.rb | spec/unit/resource/attributes_spec.rb | # frozen_string_literal: true
require "rails_helper"
module ActiveAdmin
RSpec.describe Resource, "Attributes" do
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { ActiveAdmin::Namespace.new application, :admin }
let(:resource_config) { ActiveAdmin::Resource.new namespace, Post }
describe "#resource_attributes" do
subject do
resource_config.resource_attributes
end
it "should return attributes hash" do
expect(subject).to eq(
author_id: :author,
body: :body,
created_at: :created_at,
custom_category_id: :category,
foo_id: :foo_id,
position: :position,
published_date: :published_date,
starred: :starred,
title: :title,
updated_at: :updated_at)
end
it "does not return sensitive attributes" do
keep = ActiveAdmin.application.filter_attributes
ActiveAdmin.application.filter_attributes = [:published_date]
expect(subject).to_not include :published_date
ActiveAdmin.application.filter_attributes = keep
end
context "when resource has a counter cache" do
subject { ActiveAdmin::Resource.new(namespace, Category).resource_attributes }
it "should not include counter cache column" do
expect(subject.keys).not_to include(:posts_count)
end
end
context "when resource has a 'counter cache'-like column" do
subject { ActiveAdmin::Resource.new(namespace, User).resource_attributes }
it "should include that attribute" do
expect(subject).to include(sign_in_count: :sign_in_count)
end
end
end
describe "#association_columns" do
subject do
resource_config.association_columns
end
it "should return associations" do
expect(subject).to eq([:author, :category])
end
end
describe "#content_columns" do
subject do
resource_config.content_columns
end
it "should return columns without associations" do
expect(subject).to eq([:title, :body, :published_date, :position, :starred, :foo_id, :created_at, :updated_at])
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/resource/scopes_spec.rb | spec/unit/resource/scopes_spec.rb | # frozen_string_literal: true
require "rails_helper"
module ActiveAdmin
RSpec.describe Resource, "Scopes" do
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { Namespace.new(application, :admin) }
def config(options = {})
@config ||= Resource.new(namespace, Category, options)
end
describe "adding a scope" do
it "should add a scope" do
config.scope :published
expect(config.scopes.first).to be_a(ActiveAdmin::Scope)
expect(config.scopes.first.name).to eq "Published"
end
it "should retrieve a scope by its id" do
config.scope :published
expect(config.get_scope_by_id(:published).name).to eq "Published"
end
it "should retrieve a string scope with spaces by its id without conflicts" do
aspace_1 = config.scope "a space"
aspace_2 = config.scope "as pace"
expect(config.get_scope_by_id(aspace_1.id).name).to eq "a space"
expect(config.get_scope_by_id(aspace_2.id).name).to eq "as pace"
end
it "should not add a scope with the same name twice" do
config.scope :published
config.scope :published
expect(config.scopes.size).to eq 1
end
it "should update a scope with the same id" do
config.scope :published
expect(config.scopes.first.scope_block).to eq nil
config.scope(:published) {}
expect(config.scopes.first.scope_block).to_not eq nil
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/helpers/scope_chain_spec.rb | spec/unit/helpers/scope_chain_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::ScopeChain do
include ActiveAdmin::ScopeChain
describe "#scope_chain" do
let(:relation) { double }
context "when Scope has a scope method" do
let(:scope) { ActiveAdmin::Scope.new :published }
it "should call the method on the relation and return it" do
expect(relation).to receive(:published).and_return(:scoped_relation)
expect(scope_chain(scope, relation)).to eq :scoped_relation
end
end
context "when Scope has the scope method method ':all'" do
let(:scope) { ActiveAdmin::Scope.new :all }
it "should return the relation" do
expect(scope_chain(scope, relation)).to eq relation
end
end
context "when Scope has a name and a scope block" do
let(:scope) { ActiveAdmin::Scope.new("My Scope") { |s| :scoped_relation } }
it "should instance_exec the block and return it" do
expect(scope_chain(scope, relation)).to eq :scoped_relation
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/authorization/controller_authorization_spec.rb | spec/unit/authorization/controller_authorization_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe "Controller Authorization", type: :controller do
let(:authorization) { controller.send(:active_admin_authorization) }
before do
load_resources { ActiveAdmin.register Post }
@controller = Admin::PostsController.new
allow(authorization).to receive(:authorized?)
end
it "should authorize the index action" do
expect(authorization).to receive(:authorized?).with(auth::READ, Post).and_return true
get :index
expect(response).to be_successful
end
it "should authorize the new action" do
expect(authorization).to receive(:authorized?).with(auth::NEW, an_instance_of(Post)).and_return true
get :new
expect(response).to be_successful
end
it "should authorize the create action with the new resource" do
expect(authorization).to receive(:authorized?).with(auth::CREATE, an_instance_of(Post)).and_return true
post :create
expect(response).to redirect_to action: "show", id: Post.last.id
end
it "should redirect when the user isn't authorized" do
expect(authorization).to receive(:authorized?).with(auth::READ, Post).and_return false
get :index
expect(response).to redirect_to "/admin"
end
private
def auth
ActiveAdmin::Authorization
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/authorization/index_overriding_spec.rb | spec/unit/authorization/index_overriding_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe "Index overriding", type: :controller do
before do
load_resources { ActiveAdmin.register Post }
@controller = Admin::PostsController.new
@controller.instance_eval do
def index
super do
render body: "Rendered from passed block"
return
end
end
end
end
it "should call block passed to overridden index" do
get :index
expect(response.body).to eq "Rendered from passed block"
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/authorization/authorization_adapter_spec.rb | spec/unit/authorization/authorization_adapter_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::AuthorizationAdapter do
let(:adapter) { ActiveAdmin::AuthorizationAdapter.new(double, double) }
describe "#authorized?" do
it "should always return true" do
expect(adapter.authorized?(:read, "Resource")).to eq true
end
end
describe "#scope_collection" do
it "should return the collection unscoped" do
collection = double
expect(adapter.scope_collection(collection, ActiveAdmin::Auth::READ)).to eq collection
end
end
describe "using #normalized in a subclass" do
let(:auth_class) do
Class.new(ActiveAdmin::AuthorizationAdapter) do
def authorized?(action, subject = nil)
case subject
when normalized(String)
true
else
false
end
end
end
end
let(:adapter) { auth_class.new(double, double) }
it "should match against a class" do
expect(adapter.authorized?(:read, String)).to eq true
end
it "should match against an instance" do
expect(adapter.authorized?(:read, "String")).to eq true
end
it "should not match a different class" do
expect(adapter.authorized?(:read, Hash)).to eq false
end
it "should not match a different instance" do
expect(adapter.authorized?(:read, {})).to eq false
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/namespace/register_resource_spec.rb | spec/unit/namespace/register_resource_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Namespace, "registering a resource" do
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { ActiveAdmin::Namespace.new(application, :super_admin) }
let(:menu) { namespace.fetch_menu(:default) }
after { namespace.unload! }
context "with no configuration" do
before do
namespace.register Category
end
it "should store the namespaced registered configuration" do
expect(namespace.resources.keys).to include("Category")
end
it "should create a new controller in the default namespace" do
expect(defined?(SuperAdmin::CategoriesController)).to eq "constant"
end
it "should not create the dashboard controller" do
expect(defined?(SuperAdmin::DashboardController)).to_not eq "constant"
end
it "should create a menu item" do
expect(menu["Categories"]).to be_a ActiveAdmin::MenuItem
expect(menu["Categories"].instance_variable_get(:@url)).to be_a Proc
end
end
context "when resource class is a string" do
before do
namespace.register 'Category'
end
it "should store the namespaced registered configuration" do
expect(namespace.resources.keys).to include("Category")
end
end
context "with a block configuration" do
it "should be evaluated in the dsl" do
expect do |block|
namespace.register Category, &block
end.to yield_control
end
end
context "with a resource that's namespaced" do
before do
module ::Mock; class Resource; def self.has_many(arg1, arg2); end; end; end
namespace.register Mock::Resource
end
it "should store the namespaced registered configuration" do
expect(namespace.resources.keys).to include("Mock::Resource")
end
it "should create a new controller in the default namespace" do
expect(defined?(SuperAdmin::MockResourcesController)).to eq "constant"
end
it "should create a menu item" do
expect(menu["Mock Resources"]).to be_an_instance_of(ActiveAdmin::MenuItem)
end
it "should use the resource as the model in the controller" do
expect(SuperAdmin::MockResourcesController.resource_class).to eq Mock::Resource
end
end # context "with a resource that's namespaced"
describe "finding resource instances" do
it "should return the resource when its been registered" do
post = namespace.register Post
expect(namespace.resource_for(Post)).to eq post
end
it "should return nil when the resource has not been registered" do
expect(namespace.resource_for(Post)).to eq nil
end
it "should return the parent when the parent class has been registered and the child has not" do
user = namespace.register User
expect(namespace.resource_for(Publisher)).to eq user
end
it "should return the resource if it and it's parent were registered" do
namespace.register User
publisher = namespace.register Publisher
expect(namespace.resource_for(Publisher)).to eq publisher
end
end # describe "finding resource instances"
describe "adding to the menu" do
describe "adding as a top level item" do
before do
namespace.register Category
end
it "should add a new menu item" do
expect(menu["Categories"]).to_not eq nil
end
end # describe "adding as a top level item"
describe "adding as a child" do
before do
namespace.register Category do
menu parent: "Blog"
end
end
it "should generate the parent menu item" do
expect(menu["Blog"]).to_not eq nil
end
it "should generate its own child item" do
expect(menu["Blog"]["Categories"]).to_not eq nil
end
end # describe "adding as a child"
describe "disabling the menu" do
before do
namespace.register Category do
menu false
end
end
it "should not create a menu item" do
expect(menu["Categories"]).to eq nil
end
end # describe "disabling the menu"
describe "adding as a belongs to" do
context "when not optional" do
before do
namespace.register Post do
belongs_to :author
end
end
it "should not show up in the menu" do
expect(menu["Posts"]).to eq nil
end
end
context "when optional" do
before do
namespace.register Post do
belongs_to :author, optional: true
end
end
it "should show up in the menu" do
expect(menu["Posts"]).to_not eq nil
end
end
end
end # describe "adding to the menu"
describe "dashboard controller name" do
context "when namespaced" do
it "should be namespaced" do
namespace = ActiveAdmin::Namespace.new(application, :one)
namespace.register Category
expect(defined?(One::CategoriesController)).to eq "constant"
end
end
context "when not namespaced" do
it "should not be namespaced" do
namespace = ActiveAdmin::Namespace.new(application, :two)
namespace.register Category
expect(defined?(Two::CategoriesController)).to eq "constant"
end
end
end # describe "dashboard controller name"
end # describe "registering a resource"
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/namespace/register_page_spec.rb | spec/unit/namespace/register_page_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Namespace, "registering a page" do
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { ActiveAdmin::Namespace.new(application, :admin) }
let(:menu) { namespace.fetch_menu(:default) }
context "with no configuration" do
before do
namespace.register_page "Status"
end
it "should store the namespaced registered configuration" do
expect(namespace.resources.keys).to include("Status")
end
it "should create a new controller in the default namespace" do
expect(defined?(Admin::StatusController)).to eq "constant"
end
it "should create a menu item" do
expect(menu["Status"]).to be_an_instance_of(ActiveAdmin::MenuItem)
end
end
context "with a block configuration" do
it "should be evaluated in the dsl" do
expect do |block|
namespace.register_page "Status", &block
end.to yield_control
end
end
describe "adding to the menu" do
describe "adding as a top level item" do
before do
namespace.register_page "Status"
end
it "should add a new menu item" do
expect(menu["Status"]).to_not eq nil
end
end
describe "adding as a child" do
before do
namespace.register_page "Status" do
menu parent: "Extra"
end
end
it "should generate the parent menu item" do
expect(menu["Extra"]).to_not eq nil
end
it "should generate its own child item" do
expect(menu["Extra"]["Status"]).to_not eq nil
end
end
describe "disabling the menu" do
before do
namespace.register_page "Status" do
menu false
end
end
it "should not create a menu item" do
expect(menu["Status"]).to eq nil
end
end # describe "disabling the menu"
end # describe "adding to the menu"
describe "adding as a belongs to" do
context "when not optional" do
before do
namespace.register_page "Reports" do
belongs_to :author
end
end
it "should be excluded from the menu" do
expect(menu["Reports"]).to be_nil
end
end
context "when optional" do
before do
namespace.register_page "Reports" do
belongs_to :author, optional: true
end
end
it "should be in the menu" do
expect(menu["Reports"]).to_not be_nil
end
end
end # describe "adding as a belongs to"
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/namespace/authorization_spec.rb | spec/unit/namespace/authorization_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Resource, "authorization" do
let(:app) { ActiveAdmin::Application.new }
let(:namespace) { ActiveAdmin::Namespace.new(app, :admin) }
let(:auth) { double }
describe "authorization_adapter" do
it "should return AuthorizationAdapter by default" do
expect(app.authorization_adapter).to eq ActiveAdmin::AuthorizationAdapter
expect(namespace.authorization_adapter).to eq ActiveAdmin::AuthorizationAdapter
end
it "should be settable on the namespace" do
namespace.authorization_adapter = auth
expect(namespace.authorization_adapter).to eq auth
end
it "should be settable on the application" do
app.authorization_adapter = auth
expect(app.authorization_adapter).to eq auth
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/view_helpers/method_or_proc_helper_spec.rb | spec/unit/view_helpers/method_or_proc_helper_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe MethodOrProcHelper do
let(:receiver) { double }
let(:context) do
obj = double receiver_in_context: receiver
obj.extend described_class
obj
end
describe "#call_method_or_exec_proc" do
it "should call the method in the context when a symbol" do
expect(context.call_method_or_exec_proc(:receiver_in_context)).to eq receiver
end
it "should call the method in the context when a string" do
expect(context.call_method_or_exec_proc("receiver_in_context")).to eq receiver
end
it "should exec a proc in the context" do
test_proc = Proc.new { raise "Success" if receiver_in_context }
expect do
context.call_method_or_exec_proc(test_proc)
end.to raise_error("Success")
end
end
describe "#call_method_or_proc_on" do
[:hello, "hello"].each do |key|
context "when a #{key.class}" do
it "should call the method on the receiver" do
expect(receiver).to receive(key).and_return "hello"
expect(context.call_method_or_proc_on(receiver, key)).to eq "hello"
end
it "should receive additional arguments" do
expect(receiver).to receive(key).with(:world).and_return "hello world"
expect(context.call_method_or_proc_on(receiver, key, :world)).to eq "hello world"
end
end
end
context "when a proc" do
it "should exec the block in the context and pass in the receiver" do
test_proc = Proc.new do |arg|
raise "Success!" if arg == receiver_in_context
end
expect do
context.call_method_or_proc_on(receiver, test_proc)
end.to raise_error("Success!")
end
it "should receive additional arguments" do
test_proc = Proc.new do |arg1, arg2|
raise "Success!" if arg1 == receiver_in_context && arg2 == "Hello"
end
expect do
context.call_method_or_proc_on(receiver, test_proc, "Hello")
end.to raise_error("Success!")
end
end
context "when a proc and exec: false" do
it "should call the proc and pass in the receiver" do
obj_not_in_context = double
test_proc = Proc.new do |arg|
raise "Success!" if arg == receiver && obj_not_in_context
end
expect do
context.call_method_or_proc_on(receiver, test_proc, exec: false)
end.to raise_error("Success!")
end
end
end
describe "#render_or_call_method_or_proc_on" do
[ :symbol, Proc.new {} ].each do |key|
context "when a #{key.class}" do
it "should call #call_method_or_proc_on" do
options = { foo: :bar }
expect(context).to receive(:call_method_or_proc_on).with(receiver, key, options).and_return("data")
expect(context.render_or_call_method_or_proc_on(receiver, key, options)).to eq "data"
end
end
end
context "when a string" do
it "should return the string" do
expect(context.render_or_call_method_or_proc_on(receiver, "string")).to eq "string"
end
end
end
describe "#render_in_context" do
let(:args) { [1, 2, 3] }
context "when a Proc" do
let(:object) { Proc.new {} }
it "should instance_exec the Proc" do
expect(receiver).to receive(:instance_exec).with(args, &object).and_return("data")
expect(context.render_in_context(receiver, object, args)).to eq "data"
end
end
context "when a Symbol" do
it "should send the symbol" do
expect(receiver).to receive(:public_send).with(:symbol, args).and_return("data")
expect(context.render_in_context(receiver, :symbol, args)).to eq "data"
end
end
context "when a Object (not Proc or String)" do
let(:object) { Object.new }
it "should return the Object" do
expect(context.render_in_context(receiver, object)).to eq object
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/generators/install_spec.rb | spec/unit/generators/install_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe "ActiveAdmin Installation" do
it "creates active_admin.css" do
expect(Rails.root.join("app/assets/stylesheets/active_admin.css")).to exist
end
it "creates tailwind config file" do
expect(Rails.root.join("tailwind-active_admin.config.js")).to exist
end
it "creates the dashboard resource" do
expect(Rails.root.join("app/admin/dashboard.rb")).to exist
end
it "creates the config initializer" do
expect(Rails.root.join("config/initializers/active_admin.rb")).to exist
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/views/components/paginated_collection_spec.rb | spec/unit/views/components/paginated_collection_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Views::PaginatedCollection do
describe "creating with the dsl" do
around do |example|
with_resources_during(example) { ActiveAdmin.register Post }
end
let(:view) do
view = mock_action_view
allow(view.request).to receive(:query_parameters).and_return page: "1"
allow(view.request).to receive(:path_parameters).and_return controller: "admin/posts", action: "index"
allow(view).to receive(:build_download_formats).and_return([:csv, :xml, :json])
view
end
# Helper to render paginated collections within an arbre context
def paginated_collection(*args)
render_arbre_component({ paginated_collection_args: args }, view) do
paginated_collection(*paginated_collection_args)
end
end
let(:collection) do
posts = [Post.new(title: "First Post"), Post.new(title: "Second Post"), Post.new(title: "Third Post")]
Kaminari.paginate_array(posts).page(1).per(5)
end
before do
allow(collection).to receive(:except) { collection } unless collection.respond_to? :except
allow(collection).to receive(:group_values) { [] } unless collection.respond_to? :group_values
end
let(:pagination) { paginated_collection collection }
it "should set :collection as the passed in collection" do
expect(pagination.find_by_class("pagination-information").first.content).to eq "Showing <b>all 3</b>"
end
it "should raise error if collection has no pagination scope" do
expect do
paginated_collection([Post.new, Post.new])
end.to raise_error(StandardError, "Collection is not a paginated scope. Set collection.page(params[:page]).per(10) before calling :paginated_collection.")
end
it "should preserve custom query params" do
allow(view.request).to receive(:query_parameters).and_return page: "1", something: "else"
pagination_content = pagination.content
expect(pagination_content).to include "/admin/posts.csv?page=1&something=else"
expect(pagination_content).to include "/admin/posts.xml?page=1&something=else"
expect(pagination_content).to include "/admin/posts.json?page=1&something=else"
end
context "when specifying :param_name option" do
let(:collection) do
posts = Array.new(10) { Post.new }
Kaminari.paginate_array(posts).page(1).per(5)
end
let(:pagination) { paginated_collection(collection, param_name: :post_page) }
it "should customize the page number parameter in pagination links" do
expect(pagination.to_s).to match(/\/admin\/posts\?post_page=2/)
end
end
context "when specifying :params option" do
let(:collection) do
posts = Array.new(10) { Post.new }
Kaminari.paginate_array(posts).page(1).per(5)
end
let(:pagination) { paginated_collection(collection, param_name: :post_page, params: { anchor: "here" }) }
it "should pass it through to Kaminari" do
expect(pagination.to_s).to match(/\/admin\/posts\?post_page=2#here/)
end
end
context "when specifying download_links: false option" do
let(:collection) do
posts = Array.new(10) { Post.new }
Kaminari.paginate_array(posts).page(1).per(5)
end
let(:pagination) { paginated_collection(collection, download_links: false) }
it "should not render download links" do
expect(pagination.find_by_tag("div").last.content).to_not match(/Download:/)
end
end
context "when specifying :entry_name option with a single item" do
let(:collection) do
posts = [Post.new]
Kaminari.paginate_array(posts).page(1).per(5)
end
let(:pagination) { paginated_collection(collection, entry_name: "message") }
it "should use :entry_name as the collection name" do
expect(pagination.find_by_class("pagination-information").first.content).to eq "Showing <b>1</b> of <b>1</b>"
end
end
context "when specifying :entry_name option with multiple items" do
let(:pagination) { paginated_collection(collection, entry_name: "message") }
it "should use :entry_name as the collection name" do
expect(pagination.find_by_class("pagination-information").first.content).to eq "Showing <b>all 3</b>"
end
end
context "when specifying :entry_name and :entries_name option with a single item" do
let(:collection) do
posts = [Post.new]
Kaminari.paginate_array(posts).page(1).per(5)
end
let(:pagination) { paginated_collection(collection, entry_name: "singular", entries_name: "plural") }
it "should use :entry_name as the collection name" do
expect(pagination.find_by_class("pagination-information").first.content).to eq "Showing <b>1</b> of <b>1</b>"
end
end
context "when specifying :entry_name and :entries_name option with a multiple items" do
let(:pagination) { paginated_collection(collection, entry_name: "singular", entries_name: "plural") }
it "should use :entries_name as the collection name" do
expect(pagination.find_by_class("pagination-information").first.content).to eq "Showing <b>all 3</b>"
end
end
context "when omitting :entry_name with a single item" do
let(:collection) do
posts = [Post.new]
Kaminari.paginate_array(posts).page(1).per(5)
end
it "should use 'post' as the collection name when there is no I18n translation" do
expect(pagination.find_by_class("pagination-information").first.content).to eq "Showing <b>1</b> of <b>1</b>"
end
it "should use 'Singular' as the collection name when there is an I18n translation" do
allow(I18n).to receive(:translate) { "Singular" }
expect(pagination.find_by_class("pagination-information").first.content).to eq "Showing <b>1</b> of <b>1</b>"
end
end
context "when omitting :entry_name with multiple items" do
it "should use 'posts' as the collection name when there is no I18n translation" do
expect(pagination.find_by_class("pagination-information").first.content).to eq "Showing <b>all 3</b>"
end
it "should use 'Plural' as the collection name when there is an I18n translation" do
allow(I18n).to receive(:translate) { "Plural" }
expect(pagination.find_by_class("pagination-information").first.content).to eq "Showing <b>all 3</b>"
end
end
context "when specifying an empty collection" do
let(:collection) do
posts = []
Kaminari.paginate_array(posts).page(1).per(5)
end
it "should display 'No entries found'" do
expect(pagination.find_by_class("pagination-information").first.content).to eq "No entries found"
end
end
context "when collection comes from find with GROUP BY" do
let(:collection) do
%w{Foo Foo Bar}.each { |title| Post.create(title: title) }
Post.select(:title).group(:title).page(1).per(5)
end
it "should display proper message (including number and not hash)" do
expect(pagination.find_by_class("pagination-information").first.content).to eq "Showing <b>all 2</b>"
end
end
context "when collection with many pages comes from find with GROUP BY" do
let(:collection) do
%w{Foo Foo Bar Baz}.each { |title| Post.create(title: title) }
Post.select(:title).group(:title).page(1).per(2)
end
it "should display proper message (including number and not hash)" do
expect(pagination.find_by_class("pagination-information").first.content.gsub(" ", " ")).
to eq "Showing <b>1-2</b> of <b>3</b>"
end
end
context "when viewing the last page of a collection that has multiple pages" do
let(:collection) do
Kaminari.paginate_array([Post.new] * 81).page(3).per(30)
end
it "should show the proper item counts" do
expect(pagination.find_by_class("pagination-information").first.content.gsub(" ", " ")).
to eq "Showing <b>61-81</b> of <b>81</b>"
end
end
context "with :pagination_total" do
let(:collection) do
Kaminari.paginate_array([Post.new] * 256).page(1).per(30)
end
describe "set to false" do
it "should not show the total item counts" do
expect(collection).not_to receive(:total_pages)
pagination = paginated_collection(collection, pagination_total: false)
info = pagination.find_by_class("pagination-information").first.content.gsub(" ", " ")
expect(info).to eq "Showing <b>1-30</b>"
end
end
describe "set to true" do
let(:pagination) { paginated_collection(collection, pagination_total: true) }
it "should show the total item counts" do
info = pagination.find_by_class("pagination-information").first.content.gsub(" ", " ")
expect(info).to eq "Showing <b>1-30</b> of <b>256</b>"
end
end
end
describe "when pagination_total is false" do
it "makes no expensive COUNT queries" do
undecorated_collection = Post.all.page(1).per(30)
expect { paginated_collection(undecorated_collection, pagination_total: false) }
.not_to perform_database_query("SELECT COUNT(*) FROM \"posts\"")
decorated_collection = controller_with_decorator("index", PostDecorator).apply_collection_decorator(undecorated_collection.reset)
expect { paginated_collection(decorated_collection, pagination_total: false) }
.not_to perform_database_query("SELECT COUNT(*) FROM \"posts\"")
end
it "makes a performant COUNT query to figure out if we are on the last page" do
# "SELECT COUNT(*) FROM (SELECT 1". Let's make sure the subquery has LIMIT and OFFSET. It shouldn't have ORDER BY
count_query = %r{SELECT COUNT\(\*\) FROM \(SELECT 1 .*FROM "posts" (?=.*OFFSET \?)(?=.*LIMIT \?)(?!.*ORDER BY)}
undecorated_collection = Post.all.page(1).per(30)
expect { paginated_collection(undecorated_collection, pagination_total: false) }
.to perform_database_query(count_query)
undecorated_sorted_collection = undecorated_collection.reset.order(id: :desc)
expect { paginated_collection(undecorated_sorted_collection, pagination_total: false) }
.to perform_database_query(count_query)
decorated_collection = controller_with_decorator("index", PostDecorator).apply_collection_decorator(undecorated_collection.reset)
expect { paginated_collection(decorated_collection, pagination_total: false) }
.to perform_database_query(count_query)
decorated_sorted_collection = controller_with_decorator("index", PostDecorator).apply_collection_decorator(undecorated_sorted_collection.reset)
expect { paginated_collection(decorated_sorted_collection, pagination_total: false) }
.to perform_database_query(count_query)
end
end
it "makes no COUNT queries to figure out the last element of each page" do
undecorated_collection = Post.all.page(1).per(30)
expect { paginated_collection(undecorated_collection) }
.not_to perform_database_query("SELECT COUNT(*) FROM (SELECT")
end
context "when specifying per_page: array option" do
let(:collection) do
posts = Array.new(10) { Post.new }
Kaminari.paginate_array(posts).page(1).per(5)
end
let(:pagination) { paginated_collection(collection, per_page: [1, 2, 3]) }
let(:pagination_html) { pagination.find_by_class("paginated-collection-footer").first }
let(:pagination_node) { Capybara.string(pagination_html.to_s) }
it "should render per_page select tag" do
expect(pagination_html.content).to match(/Per page/)
expect(pagination_node).to have_css("select option", count: 3)
end
context "with pagination_total: false" do
let(:pagination) { paginated_collection(collection, per_page: [1, 2, 3], pagination_total: false) }
it "should render per_page select tag" do
info = pagination.find_by_class("pagination-information").first.content.gsub(" ", " ")
expect(info).to eq "Showing <b>1-5</b>"
end
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/views/components/index_table_for_spec.rb | spec/unit/views/components/index_table_for_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Views::IndexAsTable::IndexTableFor do
describe "creating with the dsl" do
let(:collection) do
[Post.new(title: "First Post", starred: true)]
end
let(:active_admin_config) do
namespace = ActiveAdmin::Namespace.new(ActiveAdmin::Application.new, :admin)
namespace.batch_actions = [ActiveAdmin::BatchAction.new(:flag, "Flag") {}]
namespace
end
let(:assigns) do
{
collection: collection,
active_admin_config: active_admin_config,
resource_class: User,
}
end
let(:helpers) { mock_action_view }
context "when creating a selectable column" do
let(:table) do
render_arbre_component assigns, helpers do
insert_tag(ActiveAdmin::Views::IndexAsTable::IndexTableFor, collection, { sortable: true }) do
selectable_column(class: "selectable")
end
end
end
context "creates a table header based on the selectable column" do
let(:header) do
table.find_by_tag("th").first
end
it "with selectable column class name" do
expect(header.attributes[:class]).to include "selectable"
end
it "not sortable" do
expect(header.attributes).not_to include("data-sortable": "")
end
end
end
context "when creating an id column" do
before { allow(helpers).to receive(:url_target) { 'routing_stub' } }
def build_index_table(&block)
render_arbre_component assigns, helpers do
insert_tag(ActiveAdmin::Views::IndexAsTable::IndexTableFor, collection, { sortable: true }) do
instance_exec(&block)
end
end
end
it "use primary key as title by default" do
table = build_index_table { id_column }
header = table.find_by_tag("th").first
expect(header.content).to include("id")
end
it "supports title customization" do
table = build_index_table { id_column 'Res. Id' }
header = table.find_by_tag("th").first
expect(header.content).to include("Res. Id")
end
it "is sortable by default" do
table = build_index_table { id_column }
header = table.find_by_tag("th").first
expect(header.attributes).to include("data-sortable": "")
end
it "supports sortable: false" do
table = build_index_table { id_column sortable: false }
header = table.find_by_tag("th").first
expect(header.attributes).not_to include("data-sortable": "")
end
it "supports sortable column names" do
table = build_index_table { id_column sortable: :created_at }
header = table.find_by_tag("th").first
expect(header.attributes).to include("data-sortable": "")
end
it 'supports title customization and options' do
table = build_index_table { id_column 'Res. Id', sortable: :created_at }
header = table.find_by_tag("th").first
expect(header.content).to include("Res. Id")
expect(header.attributes).to include("data-sortable": "")
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/views/components/table_for_spec.rb | spec/unit/views/components/table_for_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Views::TableFor do
describe "creating with the dsl" do
let(:collection) do
[
Post.new(title: "First Post", starred: true),
Post.new(title: "Second Post"),
Post.new(title: "Third Post", starred: false)
]
end
let(:assigns) { { collection: collection } }
let(:helpers) { mock_action_view }
context "when creating a column using symbol argument" do
let(:table) do
render_arbre_component assigns, helpers do
table_for(collection, :title)
end
end
it "should create a table header based on the symbol" do
expect(table.find_by_tag("th").first.content).to eq "Title"
end
it "should create a table row for each element in the collection" do
expect(table.find_by_tag("tr").size).to eq 4 # 1 for head, 3 for rows
end
["First Post", "Second Post", "Third Post"].each_with_index do |content, index|
it "should create a cell with #{content}" do
expect(table.find_by_tag("td")[index].content).to eq content
end
end
end
context "when creating many columns using symbol arguments" do
let(:table) do
render_arbre_component assigns, helpers do
table_for(collection, :title, :created_at)
end
end
it "should create a table header based on the symbol" do
expect(table.find_by_tag("th").first.content).to eq "Title"
expect(table.find_by_tag("th").last.content).to eq "Created At"
end
it "should add a data attribute to each table header based on the column name" do
expect(table.find_by_tag("th").first.attributes).to include("data-column": "title")
expect(table.find_by_tag("th").last.attributes).to include("data-column": "created_at")
end
it "should create a table row for each element in the collection" do
expect(table.find_by_tag("tr").size).to eq 4 # 1 for head, 3 for rows
end
it "should create a cell for each column" do
expect(table.find_by_tag("td").size).to eq 6
end
it "should add a data attribute for each cell based on the column name" do
expect(table.find_by_tag("td").first.attributes).to include("data-column": "title")
expect(table.find_by_tag("td").last.attributes).to include("data-column": "created_at")
end
end
context "when creating a column using symbol arguments and another using block" do
let(:table) do
render_arbre_component assigns, helpers do
table_for(collection, :title) do
column :created_at
end
end
end
it "should create a table header based on the symbol" do
expect(table.find_by_tag("th").first.content).to eq "Title"
expect(table.find_by_tag("th").last.content).to eq "Created At"
end
it "should add a data attribute to each table header based on the column name" do
expect(table.find_by_tag("th").first.attributes).to include("data-column": "title")
expect(table.find_by_tag("th").last.attributes).to include("data-column": "created_at")
end
it "should create a table row for each element in the collection" do
expect(table.find_by_tag("tr").size).to eq 4 # 1 for head, 3 for rows
end
it "should create a cell for each column" do
expect(table.find_by_tag("td").size).to eq 6
end
it "should add a data attribute for each cell based on the column name" do
expect(table.find_by_tag("td").first.attributes).to include("data-column": "title")
expect(table.find_by_tag("td").last.attributes).to include("data-column": "created_at")
end
end
context "when creating a column with a symbol" do
let(:table) do
render_arbre_component assigns, helpers do
table_for(collection) do
column :title
end
end
end
it "should create a table header based on the symbol" do
expect(table.find_by_tag("th").first.content).to eq "Title"
end
it "should create a table row for each element in the collection" do
expect(table.find_by_tag("tr").size).to eq 4 # 1 for head, 3 for rows
end
["First Post", "Second Post", "Third Post"].each_with_index do |content, index|
it "should create a cell with #{content}" do
expect(table.find_by_tag("td")[index].content).to eq content
end
end
end
context "when creating many columns with symbols" do
let(:table) do
render_arbre_component assigns, helpers do
table_for(collection) do
column :title
column :created_at
end
end
end
it "should create a table header based on the symbol" do
expect(table.find_by_tag("th").first.content).to eq "Title"
expect(table.find_by_tag("th").last.content).to eq "Created At"
end
it "should add a data attribute to each table header based on the column name" do
expect(table.find_by_tag("th").first.attributes).to include("data-column": "title")
expect(table.find_by_tag("th").last.attributes).to include("data-column": "created_at")
end
it "should create a table row for each element in the collection" do
expect(table.find_by_tag("tr").size).to eq 4 # 1 for head, 3 for rows
end
it "should create a cell for each column" do
expect(table.find_by_tag("td").size).to eq 6
end
it "should add a data attribute for each cell based on the column name" do
expect(table.find_by_tag("td").first.attributes).to include("data-column": "title")
expect(table.find_by_tag("td").last.attributes).to include("data-column": "created_at")
end
end
context "when creating a column with block content" do
let(:table) do
render_arbre_component assigns, helpers do
table_for(collection) do
column :title do |post|
span(post.title)
end
end
end
end
it "should add a data attribute to each table header based on the column name" do
expect(table.find_by_tag("th").first.attributes).to include("data-column": "title")
end
[ "<span>First Post</span>",
"<span>Second Post</span>",
"<span>Third Post</span>"
].each_with_index do |content, index|
it "should create a cell with #{content}" do
expect(table.find_by_tag("td")[index].content.strip).to eq content
end
end
end
context "when creating a column with multiple block content" do
let(:table) do
render_arbre_component assigns, helpers do
table_for(collection) do
column :title do |post|
span(post.title)
span(post.title)
end
end
end
end
3.times do |index|
it "should create a cell with multiple elements in row #{index}" do
expect(table.find_by_tag("td")[index].find_by_tag("span").size).to eq 2
end
end
end
context "when creating many columns with symbols, blocks and strings" do
let(:table) do
render_arbre_component assigns, helpers do
table_for(collection) do
column "My Custom Title", :title
column :created_at, class: "datetime"
end
end
end
it "should add a data attribute to each header based on class option or the column name" do
expect(table.find_by_tag("th").first.attributes).to include("data-column": "my_custom_title")
expect(table.find_by_tag("th").last.attributes).to include("data-column": "created_at")
expect(table.find_by_tag("th").last.class_list.to_s).to eq "datetime"
end
it "should add a class to each cell based on class option" do
expect(table.find_by_tag("td").first.class_list.to_s).to eq ""
expect(table.find_by_tag("td").last.class_list.to_s).to eq "datetime"
end
it "should add a data attribute for each cell based on the column name" do
expect(table.find_by_tag("td").first.attributes).to include("data-column": "my_custom_title")
expect(table.find_by_tag("td").last.attributes).to include("data-column": "created_at")
end
end
context "when using a single record instead of a collection" do
let(:table) do
render_arbre_component nil, helpers do
table_for Post.new do
column :title
end
end
end
it "should render" do
expect(table.find_by_tag("th").first.content).to eq "Title"
end
end
context "when using a single Hash" do
let(:table) do
render_arbre_component nil, helpers do
table_for foo: 1, bar: 2 do
column :foo
column :bar
end
end
end
it "should render" do
expect(table.find_by_tag("th")[0].content).to eq "Foo"
expect(table.find_by_tag("th")[1].content).to eq "Bar"
expect(table.find_by_tag("td")[0].content).to eq "1"
expect(table.find_by_tag("td")[1].content).to eq "2"
end
end
context "when using an Array of Hashes" do
let(:table) do
render_arbre_component nil, helpers do
table_for [{ foo: 1 }, { foo: 2 }] do
column :foo
end
end
end
it "should render" do
expect(table.find_by_tag("th")[0].content).to eq "Foo"
expect(table.find_by_tag("td")[0].content).to eq "1"
expect(table.find_by_tag("td")[1].content).to eq "2"
end
end
context "when record attribute is boolean" do
let(:table) do
render_arbre_component assigns, helpers do
table_for(collection) do
column :starred
end
end
end
it "should render boolean attribute within status tag" do
expect(table.find_by_tag("span").first.class_list.to_s).to eq "status-tag"
expect(table.find_by_tag("span").first.content).to eq "Yes"
expect(table.find_by_tag("span").last.class_list.to_s).to eq "status-tag"
expect(table.find_by_tag("span").last.content).to eq "No"
end
end
context "with tbody_html option" do
let(:table) do
render_arbre_component assigns, helpers do
table_for(collection, tbody_html: { class: "my-class", data: { size: collection.size } }) do
column :starred
end
end
end
it "should render data-size attribute within tbody tag" do
tbody = table.find_by_tag("tbody").first
expect(tbody.attributes).to include(
class: "my-class",
data: { size: 3 })
end
end
context "with row_class (soft deprecated)" do
let(:table) do
render_arbre_component assigns, helpers do
table_for(collection, row_class: -> e { "starred" if e.starred }) do
column :starred
end
end
end
it "should render boolean attribute within status tag" do
trs = table.find_by_tag("tr")
expect(trs.size).to eq 4
expect(trs.first.class_list.to_s).to eq ""
expect(trs.second.class_list.to_s).to eq "starred"
expect(trs.third.class_list.to_s).to eq ""
expect(trs.fourth.class_list.to_s).to eq ""
end
end
context "with row_html options (takes precedence over deprecated row_class)" do
let(:table) do
render_arbre_component assigns, helpers do
table_for(
collection,
row_class: -> e { "foo" },
row_html: -> e {
{
class: ("starred" if e.starred),
data: { title: e.title },
}
}
) do
column :starred
end
end
end
it "should render html attributes within collection row" do
trs = table.find_by_tag("tr")
expect(trs.size).to eq 4
expect(trs.first.attributes).to be_empty
expect(trs.second.attributes).to include(class: "starred", data: { title: "First Post" })
expect(trs.third.attributes).to include(class: nil, data: { title: "Second Post" })
expect(trs.fourth.attributes).to include(class: nil, data: { title: "Third Post" })
end
end
context "when i18n option is specified" do
around do |example|
with_translation %i[activerecord attributes post title], "Name" do
example.call
end
end
let(:table) do
render_arbre_component assigns, helpers do
table_for(collection, i18n: Post) do
column :title
end
end
end
it "should use localized column key" do
expect(table.find_by_tag("th").first.content).to eq "Name"
end
end
context "when i18n option is not specified" do
around do |example|
with_translation %i[activerecord attributes post title], "Name" do
example.call
end
end
let(:collection) do
Post.create(
[
{ title: "First Post", starred: true },
{ title: "Second Post" },
]
)
Post.where(starred: true)
end
let(:table) do
render_arbre_component assigns, helpers do
table_for(collection) do
column :title
end
end
end
it "should predict localized key based on AR collection klass" do
expect(table.find_by_tag("th").first.content).to eq "Name"
end
end
end
describe "column sorting" do
def build_column(*args, &block)
ActiveAdmin::Views::TableFor::Column.new(*args, &block)
end
subject { table_column }
context "when default" do
let(:table_column) { build_column(:username) }
it { is_expected.to be_sortable }
describe "#sort_key" do
subject { super().sort_key }
it { is_expected.to eq("username") }
end
end
context "when a block given with no sort key" do
let(:table_column) { build_column("Username") {} }
it { is_expected.to be_sortable }
describe "#sort_key" do
subject { super().sort_key }
it { is_expected.to eq("Username") }
end
end
context "when a block given with a sort key" do
let(:table_column) { build_column("Username", sortable: :username) {} }
it { is_expected.to be_sortable }
describe "#sort_key" do
subject { super().sort_key }
it { is_expected.to eq("username") }
end
end
context "when a block given with virtual attribute and no sort key" do
let(:table_column) { build_column(:virtual, nil, Post) {} }
it { is_expected.not_to be_sortable }
end
context "when symbol given as a data column should be sortable" do
let(:table_column) { build_column("Username column", :username) }
it { is_expected.to be_sortable }
describe "#sort_key" do
subject { super().sort_key }
it { is_expected.to eq "username" }
end
end
context "when sortable: true with a symbol and string" do
let(:table_column) { build_column("Username column", :username, sortable: true) }
it { is_expected.to be_sortable }
describe "#sort_key" do
subject { super().sort_key }
it { is_expected.to eq "username" }
end
end
context "when sortable: false with a symbol" do
let(:table_column) { build_column(:username, sortable: false) }
it { is_expected.not_to be_sortable }
end
context "when sortable: false with a symbol and string" do
let(:table_column) { build_column("Username", :username, sortable: false) }
it { is_expected.not_to be_sortable }
end
context "when :sortable column is an association" do
let(:table_column) { build_column("Category", :category, Post) }
it { is_expected.not_to be_sortable }
end
context "when :sortable column is an association and block given" do
let(:table_column) { build_column("Category", :category, Post) {} }
it { is_expected.not_to be_sortable }
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/views/components/panel_spec.rb | spec/unit/views/components/panel_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Views::Panel do
let(:arbre_panel) do
render_arbre_component do
panel "My Title" do
span("Hello World")
end
end
end
let(:panel_html) { Capybara.string(arbre_panel.to_s) }
it "should have a title h3" do
expect(panel_html).to have_css "h3", text: "My Title"
end
it "should have a contents div" do
expect(panel_html).to have_css "div.panel-body"
end
it "should add children to the contents div" do
expect(panel_html).to have_css "div.panel-body > span", text: "Hello World"
end
context "with html-safe title" do
let(:arbre_panel) do
title_with_html = %q[Title with <abbr>HTML</abbr>].html_safe
render_arbre_component do
panel(title_with_html)
end
end
it "should allow a html_safe title" do
expect(panel_html).to have_css "h3", text: "Title with HTML"
expect(panel_html).to have_css "h3 > abbr", text: "HTML"
end
end
describe "#children?" do
let(:arbre_panel) do
render_arbre_component do
panel("A Panel")
end
end
it "returns false if no children have been added to the panel" do
expect(arbre_panel.children?).to eq false
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/views/components/status_tag_spec.rb | spec/unit/views/components/status_tag_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Views::StatusTag do
# Helper method to build StatusTag objects in an Arbre context
def status_tag(*args)
render_arbre_component(status_tag_args: args) do
status_tag(*assigns[:status_tag_args])
end
end
describe "#tag_name" do
subject { status_tag(nil).tag_name }
it { is_expected.to eq "span" }
end
context "when status is 'completed'" do
subject { status_tag("completed") }
describe "#class_list" do
subject { super().class_list.to_a }
it { is_expected.to contain_exactly("status-tag") }
end
describe "#content" do
subject { super().content }
it { is_expected.to eq "Completed" }
end
describe "#attributes" do
subject { super().attributes }
it { is_expected.to include("data-status": "completed") }
end
end
context "when status is :in_progress" do
subject { status_tag(:in_progress) }
describe "#class_list" do
subject { super().class_list.to_a }
it { is_expected.to contain_exactly("status-tag") }
end
describe "#content" do
subject { super().content }
it { is_expected.to eq "In Progress" }
end
describe "#attributes" do
subject { super().attributes }
it { is_expected.to include("data-status": "in_progress") }
end
end
context "when status is 'in_progress'" do
subject { status_tag("in_progress") }
describe "#class_list" do
subject { super().class_list.to_a }
it { is_expected.to contain_exactly("status-tag") }
end
describe "#content" do
subject { super().content }
it { is_expected.to eq "In Progress" }
end
describe "#attributes" do
subject { super().attributes }
it { is_expected.to include("data-status": "in_progress") }
end
end
context "when status is 'In progress'" do
subject { status_tag("In progress") }
describe "#class_list" do
subject { super().class_list.to_a }
it { is_expected.to contain_exactly("status-tag") }
end
describe "#content" do
subject { super().content }
it { is_expected.to eq "In Progress" }
end
describe "#attributes" do
subject { super().attributes }
it { is_expected.to include("data-status": "in_progress") }
end
end
context "when status is an empty string" do
subject { status_tag("") }
describe "#class_list" do
subject { super().class_list.to_a }
it { is_expected.to contain_exactly("status-tag") }
end
describe "#content" do
subject { super().content }
it { is_expected.to eq "" }
end
describe "#attributes" do
subject { super().attributes }
it { is_expected.to include("data-status": "") }
end
end
context "when status is 'true'" do
subject { status_tag("true") }
describe "#class_list" do
subject { super().class_list.to_a }
it { is_expected.to contain_exactly("status-tag") }
end
describe "#content" do
subject { super().content }
it { is_expected.to eq("Yes") }
end
describe "#attributes" do
subject { super().attributes }
it { is_expected.to include("data-status": "yes") }
end
end
context "when status is true" do
subject { status_tag(true) }
describe "#class_list" do
subject { super().class_list.to_a }
it { is_expected.to contain_exactly("status-tag") }
end
describe "#content" do
subject { super().content }
it { is_expected.to eq("Yes") }
end
describe "#attributes" do
subject { super().attributes }
it { is_expected.to include("data-status": "yes") }
end
end
context "when status is 'false'" do
subject { status_tag("false") }
describe "#class_list" do
subject { super().class_list.to_a }
it { is_expected.to contain_exactly("status-tag") }
end
describe "#content" do
subject { super().content }
it { is_expected.to eq("No") }
end
describe "#attributes" do
subject { super().attributes }
it { is_expected.to include("data-status": "no") }
end
end
context "when status is false" do
subject { status_tag(false) }
describe "#class_list" do
subject { super().class_list.to_a }
it { is_expected.to contain_exactly("status-tag") }
end
describe "#content" do
subject { super().content }
it { is_expected.to eq("No") }
end
describe "#attributes" do
subject { super().attributes }
it { is_expected.to include("data-status": "no") }
end
end
context "when status is nil" do
subject { status_tag(nil) }
describe "#class_list" do
subject { super().class_list.to_a }
it { is_expected.to contain_exactly("status-tag") }
end
describe "#content" do
subject { super().content }
it { is_expected.to eq("Unknown") }
end
describe "#attributes" do
subject { super().attributes }
it { is_expected.to include("data-status": "unset") }
end
describe "with locale override" do
around do |example|
with_translation %i[active_admin status_tag unset], "Unspecified" do
example.run
end
end
describe "#class_list" do
subject { super().class_list.to_a }
it { is_expected.to contain_exactly("status-tag") }
end
describe "#content" do
subject { super().content }
it { is_expected.to eq("Unspecified") }
end
describe "#attributes" do
subject { super().attributes }
it { is_expected.to include("data-status": "unset") }
end
end
end
context "when status is 'Active' and class is 'ok'" do
subject { status_tag("Active", class: "ok") }
describe "#content" do
subject { super().content }
it { is_expected.to eq "Active" }
end
describe "#class_list" do
subject { super().class_list.to_a }
it { is_expected.to contain_exactly("status-tag", "ok") }
end
describe "#attributes" do
subject { super().attributes }
it { is_expected.to include("data-status": "active") }
end
end
context "when status is 'Active' and label is 'on'" do
subject { status_tag("Active", label: "on") }
describe "#content" do
subject { super().content }
it { is_expected.to eq "on" }
end
describe "#class_list" do
subject { super().class_list.to_a }
it { is_expected.to contain_exactly("status-tag") }
end
describe "#attributes" do
subject { super().attributes }
it { is_expected.to include("data-status": "active") }
end
end
context "when status is 'So useless', class is 'woot awesome' and id is 'useless'" do
subject { status_tag("So useless", class: "woot awesome", id: "useless") }
describe "#content" do
subject { super().content }
it { is_expected.to eq "So Useless" }
end
describe "#class_list" do
subject { super().class_list.to_a }
it { is_expected.to contain_exactly("status-tag", "woot", "awesome") }
end
describe "#id" do
subject { super().id }
it { is_expected.to eq "useless" }
end
describe "#attributes" do
subject { super().attributes }
it { is_expected.to include("data-status": "so_useless") }
end
end
context "when status is set to a Fixnum" do
subject { status_tag(42) }
describe "#content" do
subject { super().content }
it { is_expected.to eq "42" }
end
describe "#class_list" do
subject { super().class_list.to_a }
it { is_expected.to contain_exactly("status-tag") }
end
describe "#attributes" do
subject { super().attributes }
it { is_expected.to_not include("data-status": "42") }
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/views/components/attributes_table_spec.rb | spec/unit/views/components/attributes_table_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Views::AttributesTable do
describe "creating with the dsl" do
let(:helpers) { mock_action_view }
let(:post) do
post = Post.new title: "Hello World", body: nil
allow(post).to receive(:id) { 1 }
allow(post).to receive(:new_record?) { false }
post
end
let(:assigns) { { post: post } }
# Loop through a few different ways to make the same table
# and ensure that they produce the same results
{
"when attributes are passed in to the builder methods" => proc {
render_arbre_component(assigns) do
attributes_table_for post, :id, :title, :body
end
},
"when attributes are built using the block" => proc {
render_arbre_component(assigns) do
attributes_table_for post do
rows :id, :title, :body
end
end
},
"when each attribute is passed in by itself" => proc {
render_arbre_component(assigns) do
attributes_table_for post do
row :id
row :title
row :body
end
end
},
"when you create each row with a custom block" => proc {
render_arbre_component(assigns) do
attributes_table_for post do
row("Id") { post.id }
row("Title") { post.title }
row("Body") { post.body }
end
end
},
"when you create each row with a string and symbol" => proc {
render_arbre_component(assigns) do
attributes_table_for post do
row "Id", :id
row "Title", :title
row "Body", :body
end
end
},
"when you create each row with a custom block that returns nil" => proc {
render_arbre_component(assigns) do
attributes_table_for post do
row("Id") { text_node post.id; nil }
row("Title") { text_node post.title; nil }
row("Body") { text_node post.body; nil }
end
end
},
}.each do |context_title, table_declaration|
context context_title do
let(:table) { instance_eval(&table_declaration) }
it "should render a div wrapper with the class '.attributes-table'" do
expect(table.tag_name).to eq "div"
expect(table.attr(:class)).to include("attributes-table")
end
it "should add id and type class" do
expect(table.class_names).to include("post")
expect(table.id).to eq "attributes_table_post_1"
end
it "should render 3 rows" do
expect(table.find_by_tag("tr").size).to eq 3
end
describe "rendering the rows" do
[
["Id", "1"],
["Title", "Hello World"],
["Body", "<span class=\"attributes-table-empty-value\">Empty</span>"]
].each_with_index do |(title, content), i|
describe "for #{title}" do
let(:current_row) { table.find_by_tag("tr")[i] }
it "should have the title '#{title}'" do
expect(current_row.find_by_tag("th").first.content).to eq title
end
it "should have the content '#{content}'" do
expect(current_row.find_by_tag("td").first.content.chomp.strip).to eq content
end
end
end
end # describe rendering rows
end
end # describe dsl styles
it "should add a data attribute for each row based on the column name" do
table = render_arbre_component(assigns) do
attributes_table_for(post) do
row :title
row :created_at
end
end
expect(table.find_by_tag("tr").first.to_s.split("\n").first.lstrip).
to eq '<tr data-row="title">'
expect(table.find_by_tag("tr").last.to_s.split("\n").first.lstrip).
to eq '<tr data-row="created_at">'
end
it "should allow html options for the row itself" do
table = render_arbre_component(assigns) do
attributes_table_for(post) do
row("Wee", class: "custom_row", style: "custom_style") {}
end
end
expect(table.find_by_tag("tr").first.to_s.split("\n").first.lstrip).
to eq '<tr class="custom_row" style="custom_style" data-row="wee">'
end
it "should allow html content inside the attributes table" do
table = render_arbre_component(assigns) do
attributes_table_for(post) do
row("ID") { span(post.id, class: "id") }
end
end
expect(table.find_by_tag("td").first.content.chomp.strip).to eq "<span class=\"id\">1</span>"
end
context "an attribute ending in _id" do
before do
post.foo_id = 23
post.author = User.new username: "john_doe", first_name: "John", last_name: "Doe"
end
it "should call the association if one exists" do
table = render_arbre_component assigns do
attributes_table_for post, :author
end
expect(table.find_by_tag("th").first.content).to eq "Author"
expect(table.find_by_tag("td").first.content).to eq "John Doe"
end
it "should not attempt to call a nonexistent association" do
table = render_arbre_component assigns do
attributes_table_for post, :foo_id
end
expect(table.find_by_tag("th").first.content).to eq "Foo"
expect(table.find_by_tag("td").first.content).to eq "23"
end
end
context "with a collection" do
let(:posts) do
[Post.new(title: "Hello World", id: 1), Post.new(title: "Multi Column", id: 2)].each_with_index do |post, index|
allow(post).to receive(:id).and_return(index + 1)
allow(post).to receive(:new_record?).and_return(false)
end
end
let(:assigns) { { posts: posts } }
let(:table) do
render_arbre_component(assigns) do
attributes_table_for posts, :id, :title
end
end
it "does not set id on the table" do
expect(table.attr(:id)).to eq nil
end
context "colgroup" do
let(:cols) { table.find_by_tag "col" }
it "contains a col for each record (plus headers)" do
expect(cols.size).to eq(2 + 1)
end
it "assigns an id to each col" do
cols[1..-1].each_with_index do |col, index|
expect(col.id).to eq "attributes_table_post_#{index + 1}"
end
end
end
context "when rendering the rows" do
it "should contain 3 columns" do
expect(table.find_by_tag("tr").first.children.size).to eq 3
end
[
["Id", "1", "2"],
["Title", "Hello World", "Multi Column"],
].each_with_index do |set, i|
describe "for #{set[0]}" do
let(:title) { set[0] }
let(:current_row) { table.find_by_tag("tr")[i] }
it "should have the title '#{set[0]}'" do
expect(current_row.find_by_tag("th").first.content).to eq title
end
context "with defined attribute name translation" do
it "should have the translated attribute name in the title" do
with_translation %i[activerecord attributes post title], "Translated Title" do
with_translation %i[activerecord attributes post id], "Translated Id" do
expect(current_row.find_by_tag("th").first.content).to eq "Translated #{title}"
end
end
end
end
set[1..-1].each_with_index do |content, index|
it "column #{index} should have the content '#{content}'" do
expect(current_row.find_by_tag("td")[index].content.chomp.strip).to eq content
end
end
end
end
end # describe rendering rows
end # with a collection
context "when using a single Hash" do
let(:table) do
render_arbre_component nil, helpers do
attributes_table_for foo: 1, bar: 2 do
row :foo
row :bar
end
end
end
it "should render" do
expect(table.find_by_tag("th")[0].content).to eq "Foo"
expect(table.find_by_tag("th")[1].content).to eq "Bar"
expect(table.find_by_tag("td")[0].content).to eq "1"
expect(table.find_by_tag("td")[1].content).to eq "2"
end
end
context "when using an Array of Hashes" do
let(:table) do
render_arbre_component nil, helpers do
attributes_table_for [{ foo: 1 }, { foo: 2 }] do
row :foo
end
end
end
it "should render" do
expect(table.find_by_tag("th")[0].content).to eq "Foo"
expect(table.find_by_tag("td")[0].content).to eq "1"
expect(table.find_by_tag("td")[1].content).to eq "2"
end
end
context "when using custom string labels with acronyms" do
let(:table) do
render_arbre_component(assigns) do
attributes_table_for post do
row("Registration ID") { post.id }
row("LMnO") { post.title }
end
end
end
it "should preserve acronym capitalization in custom string labels" do
rows = table.find_by_tag("tr")
expect(rows[0].find_by_tag("th").first.content).to eq "Registration ID"
expect(rows[1].find_by_tag("th").first.content).to eq "LMnO"
expect(rows[0].find_by_tag("th").first.content).not_to eq "Registration Id"
expect(rows[1].find_by_tag("th").first.content).not_to eq "L Mn O"
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/views/components/index_list_spec.rb | spec/unit/views/components/index_list_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Views::IndexList do
let(:custom_index_as) do
Class.new(ActiveAdmin::Component) do
def build(page_presenter, collection)
add_class "index"
resource_selection_toggle_panel if active_admin_config.batch_actions.any?
collection.each do |obj|
instance_exec(obj, &page_presenter.block)
end
end
def self.index_name
"custom"
end
end
end
describe "#index_list_renderer" do
let(:index_classes) { [ActiveAdmin::Views::IndexAsTable, custom_index_as] }
let(:collection) do
Post.create(title: "First Post", starred: true)
Post.where(nil)
end
let(:helpers) do
helpers = mock_action_view
allow(helpers).to receive(:url_for) { |url| "/?#{ url.to_query }" }
allow(helpers.request).to receive(:query_parameters).and_return as: "table", q: { title_cont: "terms" }
allow(helpers).to receive(:params).and_return(ActionController::Parameters.new(as: "table", q: { title_cont: "terms" }))
allow(helpers).to receive(:collection).and_return(collection)
helpers
end
subject do
render_arbre_component({ index_classes: index_classes }, helpers) do
insert_tag(ActiveAdmin::Views::IndexList, index_classes)
end
end
describe "#tag_name" do
subject { super().tag_name }
it { is_expected.to eq "div" }
end
it "should contain the names of available indexes in links" do
a_tags = subject.find_by_tag("a")
expect(a_tags.size).to eq 2
expect(a_tags.first.to_s).to include("Table")
expect(a_tags.last.to_s).to include("Custom")
end
it "should maintain index filter parameters" do
a_tags = subject.find_by_tag("a")
expect(a_tags.first.attributes[:href])
.to eq("/?#{ { as: "table", q: { title_cont: "terms" } }.to_query }")
expect(a_tags.last.attributes[:href])
.to eq("/?#{ { as: "custom", q: { title_cont: "terms" } }.to_query }")
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/views/components/scopes_spec.rb | spec/unit/views/components/scopes_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Views::Scopes do
describe "the scopes list" do
let(:collection) { Post.all }
let(:active_admin_config) { ActiveAdmin.register(Post) }
let(:assigns) do
{
active_admin_config: active_admin_config,
collection_before_scope: collection
}
end
let(:helpers) do
helpers = mock_action_view
allow(helpers.request)
.to receive(:path_parameters)
.and_return(controller: "admin/posts", action: "index")
helpers
end
let(:configured_scopes) do
[
ActiveAdmin::Scope.new(:all),
ActiveAdmin::Scope.new(:published) { |posts| posts.where.not(published_date: nil) }
]
end
let(:scope_options) do
{ scope_count: true }
end
let(:scopes) do
scopes_to_render = configured_scopes
options = scope_options
render_arbre_component assigns, helpers do
insert_tag(ActiveAdmin::Views::Scopes, scopes_to_render, options)
end
end
before do
allow(ActiveAdmin::AsyncCount).to receive(:new).and_call_original
end
around do |example|
with_resources_during(example) { active_admin_config }
end
it "renders the scopes component" do
html = Capybara.string(scopes.to_s)
expect(html).to have_css("div.scopes")
configured_scopes.each do |scope|
expect(html).to have_css("a[href='/admin/posts?scope=#{scope.id}']")
end
end
context "when scopes are configured to query their counts asynchronously" do
let(:configured_scopes) do
[
ActiveAdmin::Scope.new(:all, nil, show_count: :async),
ActiveAdmin::Scope.new(:published, nil, show_count: :async) { |posts| posts.where.not(published_date: nil) }
]
end
it "raises an error when ActiveRecord async_count is unavailable", unless: Post.respond_to?(:async_count) do
expect { scopes }.to raise_error(ActiveAdmin::AsyncCount::NotSupportedError, %r{does not support :async_count})
end
context "when async_count is available in Rails", if: Post.respond_to?(:async_count) do
it "uses AsyncCounts" do
scopes
expect(ActiveAdmin::AsyncCount).to have_received(:new).with(Post.all)
expect(ActiveAdmin::AsyncCount).to have_received(:new).with(Post.where.not(published_date: nil))
end
context "when an individual scope is configured to show its count async" do
let(:configured_scopes) do
[
ActiveAdmin::Scope.new(:all),
ActiveAdmin::Scope.new(:published, nil, show_count: :async) { |posts| posts.where.not(published_date: nil) }
]
end
it "only uses AsyncCounts for the configured scopes" do
scopes
expect(ActiveAdmin::AsyncCount).not_to have_received(:new).with(Post.all)
expect(ActiveAdmin::AsyncCount).to have_received(:new).with(Post.where.not(published_date: nil))
end
end
context "when an individual scope is configured to hide its count" do
let(:configured_scopes) do
[
ActiveAdmin::Scope.new(:all, nil, show_count: false),
ActiveAdmin::Scope.new(:published, nil, show_count: :async) { |posts| posts.where.not(published_date: nil) }
]
end
it "only uses AsyncCounts for the configured scopes" do
scopes
expect(ActiveAdmin::AsyncCount).not_to have_received(:new).with(Post.all)
expect(ActiveAdmin::AsyncCount).to have_received(:new).with(Post.where.not(published_date: nil))
end
end
context "when a scope is not to be displayed" do
let(:configured_scopes) do
[
ActiveAdmin::Scope.new(:all, nil, show_count: :async, if: -> { false })
]
end
it "avoids AsyncCounts" do
scopes
expect(ActiveAdmin::AsyncCount).not_to have_received(:new)
end
end
end
context "when :show_count is configured as false" do
let(:scope_options) do
{ scope_count: false }
end
it "avoids AsyncCounts" do
scopes
expect(ActiveAdmin::AsyncCount).not_to have_received(:new)
end
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/filters/active_spec.rb | spec/unit/filters/active_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Filters::Active do
let(:resource) do
namespace = ActiveAdmin::Namespace.new(ActiveAdmin::Application.new, :admin)
namespace.register(Post)
end
subject { described_class.new(resource, search) }
let(:params) do
::ActionController::Parameters.new(q: { author_id_eq: 1 })
end
let(:search) do
Post.ransack(params[:q])
end
it "should have filters" do
expect(subject.filters.size).to eq(1)
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/filters/active_filter_spec.rb | spec/unit/filters/active_filter_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Filters::ActiveFilter do
let(:namespace) do
ActiveAdmin::Namespace.new(ActiveAdmin::Application.new, :admin)
end
let(:resource) do
namespace.register(Post)
end
let(:user) { User.create! first_name: "John", last_name: "Doe" }
let(:category) { Category.create! name: "Category" }
let(:post) { Post.create! title: "Hello World", category: category, author: user }
let(:search) do
Post.ransack(title_eq: post.title)
end
let(:condition) do
search.conditions[0]
end
subject do
ActiveAdmin::Filters::ActiveFilter.new(resource, condition)
end
it "should have valid values" do
expect(subject.values).to eq([post.title])
end
describe "label" do
context "by default" do
it "should have valid label" do
expect(subject.label).to eq("Title equals")
end
end
context "with formtastic translations" do
it "should pick up formtastic label" do
with_translation %i[formtastic labels title], "Supertitle" do
expect(subject.label).to eq("Supertitle equals")
end
end
end
end
it "should pick predicate name translation" do
expect(subject.predicate_name).to eq(I18n.t("ransack.predicates.eq"))
end
context "search by belongs_to association" do
let(:search) do
Post.ransack(custom_category_id_eq: category.id)
end
it "should have valid values" do
expect(subject.values[0]).to be_a(Category)
end
it "should have valid label" do
expect(subject.label).to eq("Category equals")
end
it "should pick predicate name translation" do
expect(subject.predicate_name).to eq(Ransack::Translate.predicate("eq"))
end
end
context "search by polymorphic association" do
let(:resource) do
namespace.register(ActiveAdmin::Comment)
end
let(:search) do
ActiveAdmin::Comment.ransack(resource_id_eq: post.id, resource_type_eq: post.class.to_s)
end
context "id filter" do
let(:condition) do
search.conditions[0]
end
it "should have valid values" do
expect(subject.values[0]).to eq(post.id)
end
it "should have valid label" do
expect(subject.label).to eq("Resource equals")
end
end
context "type filter" do
let(:condition) do
search.conditions[1]
end
it "should have valid values" do
expect(subject.values[0]).to eq(post.class.to_s)
end
it "should have valid label" do
expect(subject.label).to eq("Resource type equals")
end
end
end
context "search by has many association" do
let(:resource) do
namespace.register(Category)
end
let(:search) do
Category.ransack(posts_id_eq: post.id)
end
it "should have valid values" do
expect(subject.values[0]).to be_a(Post)
end
it "should have valid label" do
expect(subject.label).to eq("Post equals")
end
context "search by has many through association" do
let(:resource) do
namespace.register(User)
end
let(:search) do
User.ransack(posts_category_id_eq: category.id)
end
it "should have valid values" do
expect(subject.values[0]).to be_a(Category)
end
it "should have valid label" do
expect(subject.label).to eq("Category equals")
end
end
end
context "search has no matching records" do
let(:search) { Post.ransack(author_id_eq: "foo") }
it "should not produce and error" do
expect { subject.values }.not_to raise_error
end
it "should return an enumerable" do
expect(subject.values).to respond_to(:map)
end
end
context "a label is set on the filter" do
it "should use the filter label as the label prefix" do
label = "#{user.first_name}'s Post Title"
resource.add_filter(:title, label: label)
expect(subject.label).to eq("#{label} equals")
end
it "should use the filter label as the label prefix" do
label = proc { "#{user.first_name}'s Post Title" }
resource.add_filter(:title, label: label)
expect(subject.label).to eq("#{label.call} equals")
end
context "when filter condition has a predicate" do
let(:search) do
Post.ransack(title_cont: "Hello")
end
it "should use the filter label as the label prefix" do
label = "#{user.first_name}'s Post"
resource.add_filter(:title_cont, label: label)
expect(subject.label).to eq("#{label} contains")
end
end
context "when filter condition has multiple fields" do
let(:search) do
Post.ransack(title_or_body_cont: "Hello World")
end
it "should use the filter label as the label prefix" do
label = "#{user.first_name}'s Post"
resource.add_filter(:title_or_body_cont, label: label)
expect(subject.label).to eq("#{label} contains")
end
end
end
context "the association uses a different primary_key than the related class' primary_key" do
let(:resource_klass) do
Class.new(Post) do
belongs_to :kategory, class_name: "Category", primary_key: :name, foreign_key: :title
def self.name
"SuperPost"
end
end
end
let(:resource) do
namespace.register(resource_klass)
end
let(:user) { User.create! first_name: "John", last_name: "Doe" }
let!(:category) { Category.create! name: "Category" }
let(:post) { resource_klass.create! title: "Category", author: user }
let(:search) do
resource_klass.ransack(title_eq: post.title)
end
it "should use the association's primary key to find the associated record" do
stub_const("::SuperPost", resource_klass)
resource.add_filter(:kategory)
expect(subject.values.first).to eq category
end
end
context "when the resource has a custom primary key" do
let(:resource_klass) do
Class.new(Store) do
self.primary_key = "name"
belongs_to :user
def self.name
"SubStore"
end
end
end
let(:resource) do
namespace.register(resource_klass)
end
let(:user) { User.create! first_name: "John", last_name: "Doe" }
let(:search) do
resource_klass.ransack(user_id_eq: user.id)
end
it "should use the association's primary key to find the associated record" do
stub_const("::#{resource_klass.name}", resource_klass)
expect(subject.values.first).to eq user
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/filters/resource_spec.rb | spec/unit/filters/resource_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::Filters::ResourceExtension do
let(:resource) do
namespace = ActiveAdmin::Namespace.new(ActiveAdmin::Application.new, :admin)
namespace.register(Post)
end
it "should return a Hash" do
expect(resource.filters).to be_a Hash
end
it "should return the defaults if no filters are set" do
expect(resource.filters.keys).to match_array(
[
:author, :body, :category, :created_at, :custom_created_at_searcher, :custom_title_searcher, :custom_searcher_numeric, :position, :published_date, :starred, :taggings, :tags, :title, :updated_at, :foo_id
]
)
end
it "should not have defaults when filters are disabled on the resource" do
resource.filters = false
expect(resource.filters).to be_empty
end
it "should not have defaults when the filters are disabled on the namespace" do
resource.namespace.filters = false
expect(resource.filters).to be_empty
end
it "should not have defaults when the filters are disabled on the application" do
resource.namespace.application.filters = false
expect(resource.filters).to be_empty
end
it "should return the defaults without associations if default association filters are disabled on the namespace" do
resource.namespace.include_default_association_filters = false
expect(resource.filters.keys).to match_array(
[
:body, :created_at, :custom_created_at_searcher, :custom_title_searcher, :custom_searcher_numeric, :position, :published_date, :starred, :title, :updated_at, :foo_id
]
)
end
describe "removing a filter" do
it "should work" do
expect(resource.filters.keys).to include :author
resource.remove_filter :author
expect(resource.filters.keys).to_not include :author
end
it "should work as a string" do
expect(resource.filters.keys).to include :author
resource.remove_filter "author"
expect(resource.filters.keys).to_not include :author
end
it "should be lazy" do
expect(resource).to_not receive :default_filters # this hits the DB
resource.remove_filter :author
end
it "should not prevent the default filters from being added" do
resource.remove_filter :author
expect(resource.filters).to_not be_empty
end
it "should raise an exception when filters are disabled" do
resource.filters = false
expect { resource.remove_filter :author }.to raise_error(ActiveAdmin::Filters::Disabled, /Cannot remove a filter/)
end
end
describe "removing a multiple filters inline" do
it "should work" do
expect(resource.filters.keys).to include :author, :body
resource.remove_filter :author, :body
expect(resource.filters.keys).to_not include :author, :body
end
end
describe "adding a filter" do
it "should work" do
resource.add_filter :title
expect(resource.filters).to eq title: {}
end
it "should work as a string" do
resource.add_filter "title"
expect(resource.filters).to eq title: {}
end
it "should work with specified options" do
resource.add_filter :title, as: :string
expect(resource.filters).to eq title: { as: :string }
end
it "should override an existing filter" do
resource.add_filter :title, one: :two
resource.add_filter :title, three: :four
expect(resource.filters).to eq title: { three: :four }
end
it "should preserve default filters" do
resource.preserve_default_filters!
resource.add_filter :count, as: :string
expect(resource.filters.keys).to match_array(
[
:author, :body, :category, :count, :created_at, :custom_created_at_searcher, :custom_title_searcher, :custom_searcher_numeric, :position, :published_date, :starred, :taggings, :tags, :title, :updated_at, :foo_id
]
)
end
it "should raise an exception when filters are disabled" do
resource.filters = false
expect { resource.add_filter :title }.to raise_error(ActiveAdmin::Filters::Disabled, /Cannot add a filter/)
end
end
it "should reset filters" do
resource.add_filter :title
expect(resource.filters.size).to eq 1
resource.reset_filters!
expect(resource.filters.size).to be > 1
end
it "should add a sidebar section for the filters" do
expect(resource.sidebar_sections.first.name).to eq "filters"
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/localizers/resource_localizer_spec.rb | spec/unit/localizers/resource_localizer_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.shared_examples_for "ActiveAdmin::Localizers::ResourceLocalizer" do
it "should use proper translation" do
string = ActiveAdmin::Localizers::ResourceLocalizer.t(action, model: model, model_name: model_name)
expect(string).to eq translation
end
it "should accessible via ActiveAdmin::Localizers" do
resource = double(resource_label: model, resource_name: double(i18n_key: model_name))
localizer = ActiveAdmin::Localizers.resource(resource)
expect(localizer.t(action)).to eq translation
end
end
RSpec.describe ActiveAdmin::Localizers::ResourceLocalizer do
let(:action) { "new_model" }
let(:model) { "Comment" }
let(:model_name) { "comment" }
it_behaves_like "ActiveAdmin::Localizers::ResourceLocalizer" do
let(:translation) { "New Comment" }
end
describe "model action specified" do
around do |example|
with_translation %i[active_admin resources comment new_model], "Write comment" do
example.call
end
end
it_behaves_like "ActiveAdmin::Localizers::ResourceLocalizer" do
let(:translation) { "Write comment" }
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/resource_controller/polymorphic_routes_spec.rb | spec/unit/resource_controller/polymorphic_routes_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::ResourceController::PolymorphicRoutes, type: :controller do
let(:klass) { Admin::PostsController }
%w(polymorphic_url polymorphic_path).each do |method|
describe method do
let(:add_extra_routes) {}
let(:params) { {} }
before do
load_resources { post_config }
add_extra_routes
@controller = klass.new
get :index, params: params
end
context "without belongs_to" do
let(:post_config) { ActiveAdmin.register Post }
let(:post) { Post.create! title: "Hello World" }
it "works with no parent" do
expect(controller.send(method, [:admin, post])).to include("/admin/posts/#{post.id}")
end
end
context "with belongs_to" do
let(:user) { User.create! }
let(:post) { Post.create! title: "Hello World", author: user }
let(:post_config) do
ActiveAdmin.register User
ActiveAdmin.register Post do
belongs_to :user, optional: true
end
end
%w(posts user_posts).each do |current_page|
context "within the #{current_page} page" do
let(:filter_param) { current_page.sub(/_?posts/, "").presence }
let(:params) { filter_param ? { "#{filter_param}_id" => send(filter_param).id } : {} }
it "works with no parent" do
expect(controller.send(method, [:admin, post])).to include("/admin/posts/#{post.id}")
end
it "works with a user as parent" do
expect(controller.send(method, [:admin, user, post])).to include("/admin/users/#{user.id}/posts/#{post.id}")
end
end
end
end
context "with multiple belongs_to (not fully supported yet)" do
let(:user) { User.create! }
let(:category) { Category.create! name: "Category" }
let(:post) { Post.create! title: "Hello World", author: user, category: category }
let(:post_config) do
ActiveAdmin.register User
ActiveAdmin.register Category
ActiveAdmin.register Post do
belongs_to :category, optional: true
belongs_to :user, optional: true
end
end
let(:add_extra_routes) do
routes.draw do
ActiveAdmin.routes(self)
namespace :admin do
resources :posts
resources :users do
resources :posts
end
resources :categories do
resources :posts
end
end
end
end
%w(posts category_posts user_posts).each do |current_page|
context "within the #{current_page} page" do
let(:filter_param) { current_page.sub(/_?posts/, "").presence }
let(:params) { filter_param ? { "#{filter_param}_id" => send(filter_param).id } : {} }
it "works with no parent" do
expect(controller.send(method, [:admin, post])).to include("/admin/posts/#{post.id}")
end
it "works with a user as parent" do
expect(controller.send(method, [:admin, user, post])).to include("/admin/users/#{user.id}/posts/#{post.id}")
end
it "works with a category as parent" do
expect(controller.send(method, [:admin, category, post])).to include("/admin/categories/#{category.id}/posts/#{post.id}")
end
end
end
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/resource_controller/data_access_spec.rb | spec/unit/resource_controller/data_access_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::ResourceController::DataAccess do
around do |example|
with_resources_during(example) do
config
end
end
let(:config) do
ActiveAdmin.register Post do
end
end
let(:http_params) do
{}
end
let(:params) do
ActionController::Parameters.new(http_params)
end
let(:controller) do
rc = Admin::PostsController.new
allow(rc).to receive(:params) do
params
end
rc
end
describe "searching" do
let(:ransack_options) { { auth_object: controller.send(:active_admin_authorization) } }
let(:http_params) { { q: {} } }
it "should call the search method" do
chain = double "ChainObj"
expect(chain).to receive(:ransack).with(params[:q], ransack_options).once.and_return(Post.ransack)
controller.send :apply_filtering, chain
end
context "params includes empty values" do
let(:http_params) do
{ q: { id_eq: 1, position_eq: "" } }
end
it "should return relation without empty filters" do
expect(Post).to receive(:ransack).with(params[:q], ransack_options).once.and_wrap_original do |original, *args|
chain = original.call(*args)
expect(chain.conditions.size).to eq(1)
chain
end
controller.send :apply_filtering, Post
end
end
end
describe "sorting" do
context "valid clause" do
let(:http_params) { { order: "id_asc" } }
it "reorders chain" do
chain = double "ChainObj"
expect(chain).to receive(:reorder).with('"posts"."id" asc').once.and_return(Post.ransack)
controller.send :apply_sorting, chain
end
end
context "invalid clause" do
let(:http_params) { { order: "_asc" } }
it "returns chain untouched" do
chain = double "ChainObj"
expect(chain).not_to receive(:reorder)
expect(controller.send(:apply_sorting, chain)).to eq chain
end
end
context "custom strategy" do
before do
expect(controller.send(:active_admin_config)).to receive(:ordering).twice.and_return(
{
published_date: proc do |order_clause|
[order_clause.to_sql, "NULLS LAST"].join(" ") if order_clause.order == "desc"
end
}.with_indifferent_access
)
end
context "when params applicable" do
let(:http_params) { { order: "published_date_desc" } }
it "reorders chain" do
chain = double "ChainObj"
expect(chain).to receive(:reorder).with('"posts"."published_date" desc NULLS LAST').once.and_return(Post.ransack)
controller.send :apply_sorting, chain
end
end
context "when params not applicable" do
let(:http_params) { { order: "published_date_asc" } }
it "reorders chain" do
chain = double "ChainObj"
expect(chain).to receive(:reorder).with('"posts"."published_date" asc').once.and_return(Post.ransack)
controller.send :apply_sorting, chain
end
end
end
end
describe "scoping" do
context "when no current scope" do
it "should set collection_before_scope to the chain and return the chain" do
chain = double "ChainObj"
expect(controller.send(:apply_scoping, chain)).to eq chain
expect(controller.send(:collection_before_scope)).to eq chain
end
end
context "when current scope" do
it "should set collection_before_scope to the chain and return the scoped chain" do
chain = double "ChainObj"
scoped_chain = double "ScopedChain"
current_scope = double "CurrentScope"
allow(controller).to receive(:current_scope) { current_scope }
expect(controller).to receive(:scope_chain).with(current_scope, chain) { scoped_chain }
expect(controller.send(:apply_scoping, chain)).to eq scoped_chain
expect(controller.send(:collection_before_scope)).to eq chain
end
end
end
describe "includes" do
context "with no includes" do
it "should return the chain" do
chain = double "ChainObj"
expect(controller.send(:apply_includes, chain)).to eq chain
end
end
context "with includes" do
it "should return the chain with the includes" do
chain = double "ChainObj"
chain_with_includes = double "ChainObjWithIncludes"
expect(chain).to receive(:includes).with(:taggings, :author).and_return(chain_with_includes)
expect(controller.send(:active_admin_config)).to receive(:includes).twice.and_return([:taggings, :author])
expect(controller.send(:apply_includes, chain)).to eq chain_with_includes
end
end
end
describe "pagination" do
let(:collection) do
Post.create!
Post.all
end
let(:config) do
ActiveAdmin.register Post do
config.per_page = 1
end
end
context "when CSV format requested" do
let(:params) do
ActionController::Parameters.new(page: 2, format: "csv")
end
it "does not apply it" do
expect(controller.send(:apply_pagination, collection).size).to eq(1)
end
end
context "when CSV format not requested" do
let(:params) do
ActionController::Parameters.new(page: 2)
end
it "applies it" do
expect(controller.send(:apply_pagination, collection).size).to eq(0)
end
end
end
describe "find_collection" do
let(:appliers) do
ActiveAdmin::ResourceController::DataAccess::COLLECTION_APPLIES
end
let(:scoped_collection) do
double "ScopedCollectionChain"
end
before do
allow(controller).to receive(:scoped_collection).
and_return(scoped_collection)
end
it "should return chain with all appliers " do
appliers.each do |applier|
expect(controller).to receive("apply_#{applier}").
with(scoped_collection).
once.
and_return(scoped_collection)
end
expect(controller).to receive(:collection_applies).
with({}).and_call_original.once
controller.send :find_collection
end
describe "collection_applies" do
context "excepting appliers" do
let(:options) do
{ except:
[:authorization_scope, :filtering, :scoping, :collection_decorator]
}
end
it "should except appliers" do
expect(controller.send :collection_applies, options).
to eq([:sorting, :includes, :pagination])
end
end
context "specifying only needed appliers" do
let(:options) do
{ only: [:filtering, :scoping] }
end
it "should except appliers" do
expect(controller.send :collection_applies, options).to eq(options[:only])
end
end
end
end
describe "build_resource" do
let(:config) do
ActiveAdmin.register User do
permit_params :type, posts_attributes: :custom_category_id
end
end
let!(:category) { Category.create!(name: "Category") }
let(:params) do
ActionController::Parameters.new(user: { type: "User::VIP", posts_attributes: [custom_category_id: category.id] })
end
subject do
controller.send :build_resource
end
let(:controller) do
rc = Admin::UsersController.new
allow(rc).to receive(:params) do
params
end
rc
end
it "should return post with assigned attributes" do
expect(subject).to be_a(User::VIP)
end
# see issue 4548
it "should assign nested attributes once" do
expect(subject.posts.size).to eq(1)
end
context "given authorization scope" do
let(:authorization) { controller.send(:active_admin_authorization) }
it "should apply authorization scope" do
expect(authorization).to receive(:scope_collection) do |collection|
collection.where(age: "42")
end
expect(subject.age).to eq(42)
end
end
end
describe "in_paginated_batches" do
it "calls find_collection just once and disables the ActiveRecord query cache" do
expect(controller).to receive(:find_collection).once do
expect(ActiveRecord::Base.connection.query_cache_enabled).to be_falsy
Post.none
end
ActiveRecord::Base.cache do
controller.send(:in_paginated_batches, &Proc.new {})
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/spec/unit/resource_controller/decorators_spec.rb | spec/unit/resource_controller/decorators_spec.rb | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::ResourceController::Decorators do
describe "#apply_decorator" do
let(:resource) { Post.new }
let(:controller) { controller_with_decorator(action, decorator_class) }
subject(:applied) { controller.apply_decorator(resource) }
context "in show action" do
let(:action) { "show" }
context "with a Draper decorator" do
let(:decorator_class) { PostDecorator }
it { is_expected.to be_kind_of(PostDecorator) }
end
context "with a PORO decorator" do
let(:decorator_class) { PostPoroDecorator }
it { is_expected.to be_kind_of(PostPoroDecorator) }
end
end
context "in update action" do
let(:action) { "update" }
let(:decorator_class) { nil }
it { is_expected.not_to be_kind_of(PostDecorator) }
end
end
describe "#apply_collection_decorator" do
before { Post.create! }
let(:collection) { Post.where nil }
context "with a Draper decorator" do
let(:controller) { controller_with_decorator("index", PostDecorator) }
subject(:applied) { controller.apply_collection_decorator(collection) }
context "when a decorator is configured" do
context "and it is using a recent version of draper" do
it "calling certain scope collections work" do
# This is an example of one of the methods that was consistently
# failing before this feature existed
expect(applied.reorder("").count).to eq applied.count
end
it "has a good description for the generated class" do
expect(applied.class.name).to eq "Draper::CollectionDecorator of PostDecorator + ActiveAdmin"
end
end
end
end
context "with a PORO decorator" do
let(:controller) { controller_with_decorator("index", PostPoroDecorator) }
subject(:applied) { controller.apply_collection_decorator(collection) }
it "returns a presented collection" do
expect(subject).to be_kind_of(ActiveAdmin::CollectionDecorator)
expect(subject).to all(be_a(PostPoroDecorator))
end
it "has a good description for the generated class" do
expect(applied.class.name).to eq "ActiveAdmin::CollectionDecorator of PostPoroDecorator + ActiveAdmin"
end
end
end
describe "form actions" do
let(:resource) { Post.new }
let(:controller) { controller_with_decorator("edit", decorator_class) }
subject(:applied) { controller.apply_decorator(resource) }
context "when the form is not configured to decorate" do
let(:decorator_class) { nil }
it { is_expected.to be_kind_of(Post) }
end
context "when the form is configured to decorate" do
context "with a Draper decorator" do
let(:decorator_class) { PostDecorator }
it { is_expected.to be_kind_of(PostDecorator) }
end
context "with a PORO decorator" do
let(:decorator_class) { PostPoroDecorator }
it { is_expected.to be_kind_of(PostPoroDecorator) }
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin.rb | lib/active_admin.rb | # frozen_string_literal: true
require "active_support/core_ext"
require "set"
require "ransack"
require "kaminari"
require "formtastic"
require "formtastic_i18n"
require "inherited_resources"
require "arbre"
begin
require "importmap-rails"
rescue LoadError
# importmap-rails is optional
end
module ActiveAdmin
autoload :VERSION, "active_admin/version"
autoload :Application, "active_admin/application"
autoload :Authorization, "active_admin/authorization_adapter"
autoload :AuthorizationAdapter, "active_admin/authorization_adapter"
autoload :Callbacks, "active_admin/callbacks"
autoload :Component, "active_admin/component"
autoload :CanCanAdapter, "active_admin/cancan_adapter"
autoload :ControllerAction, "active_admin/controller_action"
autoload :CSVBuilder, "active_admin/csv_builder"
autoload :Dependency, "active_admin/dependency"
autoload :Devise, "active_admin/devise"
autoload :DSL, "active_admin/dsl"
autoload :FormBuilder, "active_admin/form_builder"
autoload :Inputs, "active_admin/inputs"
autoload :Localizers, "active_admin/localizers"
autoload :Menu, "active_admin/menu"
autoload :MenuCollection, "active_admin/menu_collection"
autoload :MenuItem, "active_admin/menu_item"
autoload :Namespace, "active_admin/namespace"
autoload :OrderClause, "active_admin/order_clause"
autoload :Page, "active_admin/page"
autoload :PagePresenter, "active_admin/page_presenter"
autoload :PageDSL, "active_admin/page_dsl"
autoload :PunditAdapter, "active_admin/pundit_adapter"
autoload :Resource, "active_admin/resource"
autoload :ResourceDSL, "active_admin/resource_dsl"
autoload :Scope, "active_admin/scope"
autoload :ScopeChain, "active_admin/helpers/scope_chain"
autoload :SidebarSection, "active_admin/sidebar_section"
autoload :TableBuilder, "active_admin/table_builder"
autoload :ViewHelpers, "active_admin/view_helpers"
autoload :Views, "active_admin/views"
class << self
attr_accessor :application, :importmap
def application
@application ||= ::ActiveAdmin::Application.new
end
def deprecator
@deprecator ||= ActiveSupport::Deprecation.new("4.1", "active-admin")
end
def importmap
@importmap ||= Importmap::Map.new
end
# Gets called within the initializer
def setup
application.setup!
yield(application)
application.prepare!
end
delegate :register, to: :application
delegate :register_page, to: :application
delegate :unload!, to: :application
delegate :load!, to: :application
delegate :routes, to: :application
# A callback is triggered each time (before) Active Admin loads the configuration files.
# In development mode, this will happen whenever the user changes files. In production
# it only happens on boot.
#
# The block takes the current instance of [ActiveAdmin::Application]
#
# Example:
#
# ActiveAdmin.before_load do |app|
# # Do some stuff before AA loads
# end
#
# @param [Block] block A block to call each time (before) AA loads resources
def before_load(&block)
ActiveSupport::Notifications.subscribe ActiveAdmin::Application::BeforeLoadEvent, &wrap_block_for_active_support_notifications(block)
end
# A callback is triggered each time (after) Active Admin loads the configuration files. This
# is an opportunity to hook into Resources after they've been loaded.
#
# The block takes the current instance of [ActiveAdmin::Application]
#
# Example:
#
# ActiveAdmin.after_load do |app|
# app.namespaces.each do |name, namespace|
# puts "Namespace: #{name} loaded!"
# end
# end
#
# @param [Block] block A block to call each time (after) AA loads resources
def after_load(&block)
ActiveSupport::Notifications.subscribe ActiveAdmin::Application::AfterLoadEvent, &wrap_block_for_active_support_notifications(block)
end
private
def wrap_block_for_active_support_notifications block
proc { |_name, _start, _finish, _id, payload| block.call payload[:active_admin_application] }
end
end
end
# Require things that don't support autoload
require_relative "active_admin/engine"
require_relative "active_admin/error"
# Require internal plugins
require_relative "active_admin/batch_actions"
require_relative "active_admin/filters"
# Require ORM-specific plugins
require_relative "active_admin/orm/active_record" if defined? ActiveRecord
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/activeadmin.rb | lib/activeadmin.rb | # frozen_string_literal: true
require_relative "active_admin"
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/generators/active_admin/views_generator.rb | lib/generators/active_admin/views_generator.rb | # frozen_string_literal: true
module ActiveAdmin
module Generators
class ViewsGenerator < Rails::Generators::Base
source_root File.expand_path("../../../", __dir__)
def copy_views
directory "app/views/layouts"
directory "app/views/active_admin", recursive: false
directory "app/views/active_admin/devise"
directory "app/views/active_admin/kaminari"
copy_file "app/views/active_admin/shared/_resource_comments.html.erb"
copy_file "app/views/active_admin/resource/_index_blank_slate.html.erb"
copy_file "app/views/active_admin/resource/_index_empty_results.html.erb"
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/generators/active_admin/resource/resource_generator.rb | lib/generators/active_admin/resource/resource_generator.rb | # frozen_string_literal: true
module ActiveAdmin
module Generators
class ResourceGenerator < Rails::Generators::NamedBase
desc "Registers resources with Active Admin"
source_root File.expand_path("templates", __dir__)
def generate_config_file
template "resource.rb.erb", "app/admin/#{file_path.tr('/', '_').pluralize}.rb"
end
protected
def attributes
@attributes ||= class_name.constantize.new.attributes.keys
end
def primary_key
@primary_key ||= [class_name.constantize.primary_key].flatten
end
def assignable_attributes
@assignable_attributes ||= attributes - primary_key - %w(created_at updated_at)
end
def permit_params
assignable_attributes.map { |a| a.to_sym.inspect }.join(", ")
end
def rows
attributes.map { |a| row(a) }.join("\n ")
end
def row(name)
"row :#{name.gsub(/_id$/, '')}"
end
def columns
(attributes - primary_key).map { |a| column(a) }.join("\n ")
end
def column(name)
"column :#{name.gsub(/_id$/, '')}"
end
def filters
attributes.map { |a| filter(a) }.join("\n ")
end
def filter(name)
"filter :#{name.gsub(/_id$/, '')}"
end
def form_inputs
assignable_attributes.map { |a| form_input(a) }.join("\n ")
end
def form_input(name)
"f.input :#{name.gsub(/_id$/, '')}"
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/generators/active_admin/devise/devise_generator.rb | lib/generators/active_admin/devise/devise_generator.rb | # frozen_string_literal: true
require_relative "../../../active_admin/error"
require_relative "../../../active_admin/dependency"
module ActiveAdmin
module Generators
class DeviseGenerator < Rails::Generators::NamedBase
desc "Creates an admin user and uses Devise for authentication"
argument :name, type: :string, default: "AdminUser"
class_option :registerable, type: :boolean, default: false,
desc: "Should the generated resource be registerable?"
RESERVED_NAMES = [:active_admin_user]
class_option :default_user, type: :boolean, default: true,
desc: "Should a default user be created inside the migration?"
def install_devise
begin
Dependency.devise! Dependency::Requirements::DEVISE
rescue DependencyError => e
raise ActiveAdmin::GeneratorError, "#{e.message} If you don't want to use devise, run the generator with --skip-users."
end
require "devise"
initializer_file =
File.join(destination_root, "config", "initializers", "devise.rb")
if File.exist?(initializer_file)
log :generate, "No need to install devise, already done."
else
log :generate, "devise:install"
invoke "devise:install"
end
end
def create_admin_user
if RESERVED_NAMES.include?(name.underscore)
raise ActiveAdmin::GeneratorError, "The name #{name} is reserved by Active Admin"
end
invoke "devise", [name]
end
def remove_registerable_from_model
unless options[:registerable]
model_file = File.join(destination_root, "app", "models", "#{file_path}.rb")
gsub_file model_file, /\:registerable([.]*,)?/, ""
end
end
def set_namespace_for_path
routes_file = File.join(destination_root, "config", "routes.rb")
gsub_file routes_file, /devise_for :#{plural_table_name}$/, "devise_for :#{plural_table_name}, ActiveAdmin::Devise.config"
end
def add_default_user_to_seed
seeds_paths = Rails.application.paths["db/seeds.rb"]
seeds_file = seeds_paths.existent.first
return if seeds_file.nil? || !options[:default_user]
create_user_code = "#{class_name}.create!(email: 'admin@example.com', password: 'password', password_confirmation: 'password') if Rails.env.development?"
append_to_file seeds_file, create_user_code
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/generators/active_admin/assets/assets_generator.rb | lib/generators/active_admin/assets/assets_generator.rb | # frozen_string_literal: true
module ActiveAdmin
module Generators
class AssetsGenerator < Rails::Generators::Base
source_root File.expand_path("templates", __dir__)
def install_assets
remove_file "app/assets/stylesheets/active_admin.scss"
remove_file "app/assets/javascripts/active_admin.js"
template "active_admin.css", "app/assets/stylesheets/active_admin.css"
template "tailwind.config.js", "tailwind-active_admin.config.js"
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/generators/active_admin/page/page_generator.rb | lib/generators/active_admin/page/page_generator.rb | # frozen_string_literal: true
module ActiveAdmin
module Generators
class PageGenerator < Rails::Generators::NamedBase
source_root File.expand_path("templates", __dir__)
def generate_config_file
template "page.rb", "app/admin/#{file_path.tr('/', '_')}.rb"
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/generators/active_admin/page/templates/page.rb | lib/generators/active_admin/page/templates/page.rb | # frozen_string_literal: true
ActiveAdmin.register_page "<%= class_name %>" do
content do
# your content
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/generators/active_admin/install/install_generator.rb | lib/generators/active_admin/install/install_generator.rb | # frozen_string_literal: true
require "rails/generators/active_record"
module ActiveAdmin
module Generators
class InstallGenerator < ActiveRecord::Generators::Base
desc "Installs Active Admin and generates the necessary migrations"
argument :name, type: :string, default: "AdminUser"
hook_for :users, default: "devise", desc: "Admin user generator to run. Skip with --skip-users"
class_option :skip_comments, type: :boolean, default: false, desc: "Skip installation of comments"
source_root File.expand_path("templates", __dir__)
def copy_initializer
@underscored_user_name = name.underscore.tr("/", "_")
@use_authentication_method = options[:users].present?
@skip_comments = options[:skip_comments]
template "active_admin.rb.erb", "config/initializers/active_admin.rb"
end
def setup_directory
empty_directory "app/admin"
template "dashboard.rb", "app/admin/dashboard.rb"
if options[:users].present?
@user_class = name
template "admin_users.rb.erb", "app/admin/#{name.underscore.pluralize}.rb"
end
end
def setup_routes
if options[:users] # Ensure Active Admin routes occur after Devise routes so that Devise has higher priority
inject_into_file "config/routes.rb", "\n ActiveAdmin.routes(self)", after: /devise_for .*, ActiveAdmin::Devise\.config/
else
route "ActiveAdmin.routes(self)"
end
end
def create_assets
generate "active_admin:assets"
end
def create_migrations
unless options[:skip_comments]
migration_template "migrations/create_active_admin_comments.rb.erb", "db/migrate/create_active_admin_comments.rb"
end
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/generators/active_admin/install/templates/dashboard.rb | lib/generators/active_admin/install/templates/dashboard.rb | # frozen_string_literal: true
ActiveAdmin.register_page "Dashboard" do
menu priority: 1, label: proc { I18n.t("active_admin.dashboard") }
content title: proc { I18n.t("active_admin.dashboard") } do
div class: "px-4 py-16 md:py-32 text-center m-auto max-w-3xl" do
h2 "Welcome to ActiveAdmin", class: "text-base font-semibold leading-7 text-indigo-600 dark:text-indigo-500"
para "This is the default page", class: "mt-2 text-3xl sm:text-4xl font-bold text-gray-900 dark:text-gray-200"
para class: "mt-6 text-xl leading-8 text-gray-700 dark:text-gray-400" do
text_node "To update the content, edit the"
strong "app/admin/dashboard.rb"
text_node "file to get started."
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/resource.rb | lib/active_admin/resource.rb | # frozen_string_literal: true
require_relative "view_helpers/method_or_proc_helper"
require_relative "resource/action_items"
require_relative "resource/attributes"
require_relative "resource/controllers"
require_relative "resource/menu"
require_relative "resource/page_presenters"
require_relative "resource/pagination"
require_relative "resource/routes"
require_relative "resource/naming"
require_relative "resource/scopes"
require_relative "resource/includes"
require_relative "resource/scope_to"
require_relative "resource/sidebars"
require_relative "resource/belongs_to"
require_relative "resource/ordering"
require_relative "resource/model"
module ActiveAdmin
# Resource is the primary data storage for resource configuration in Active Admin
#
# When you register a resource (ActiveAdmin.register Post) you are actually creating
# a new Resource instance within the given Namespace.
#
# The instance of the current resource is available in ResourceController and views
# by calling the #active_admin_config method.
#
class Resource
# Event dispatched when a new resource is registered
RegisterEvent = "active_admin.resource.register".freeze
# The namespace this config belongs to
attr_reader :namespace
# The name of the resource class
attr_reader :resource_class_name
# An array of member actions defined for this resource
attr_reader :member_actions
# An array of collection actions defined for this resource
attr_reader :collection_actions
# The default sort order to use in the controller
attr_writer :sort_order
def sort_order
@sort_order ||= (resource_class.respond_to?(:primary_key) ? resource_class.primary_key.to_s : "id") + "_desc"
end
# Set the configuration for the CSV
attr_writer :csv_builder
# Set breadcrumb builder
attr_writer :breadcrumb
#Set order clause
attr_writer :order_clause
# Display create another checkbox on a new page
# @return [Boolean]
attr_writer :create_another
# Store a reference to the DSL so that we can dereference it during garbage collection.
attr_accessor :dsl
# The string identifying a class to decorate our resource with for the view.
# nil to not decorate.
attr_accessor :decorator_class_name
module Base
def initialize(namespace, resource_class, options = {})
@namespace = namespace
@resource_class_name = resource_class.respond_to?(:name) ? "::#{resource_class.name}" : resource_class.to_s
@options = options
@sort_order = options[:sort_order]
@member_actions = []
@collection_actions = []
end
end
include MethodOrProcHelper
include Base
include ActionItems
include Authorization
include Controllers
include Menu
include Naming
include PagePresenters
include Pagination
include Scopes
include Includes
include ScopeTo
include Sidebars
include Routes
include Ordering
include Attributes
# The class this resource wraps. If you register the Post model, Resource#resource_class
# will point to the Post class
def resource_class
resource_class_name.constantize
end
def decorator_class
decorator_class_name&.constantize
end
def resource_name_extension
@resource_name_extension ||= define_resource_name_extension(self)
end
def resource_table_name
resource_class.quoted_table_name
end
def resource_column_names
resource_class.column_names
end
def resource_quoted_column_name(column)
resource_class.connection.quote_column_name(column)
end
# Clears all the member actions this resource knows about
def clear_member_actions!
@member_actions = []
end
def clear_collection_actions!
@collection_actions = []
end
# Return only defined resource actions
def defined_actions
controller.instance_methods.map(&:to_sym) & ResourceController::ACTIVE_ADMIN_ACTIONS
end
def belongs_to(target, options = {})
@belongs_to = Resource::BelongsTo.new(self, target, options)
self.menu_item_options = false if @belongs_to.required?
options[:class_name] ||= @belongs_to.resource.resource_class_name if @belongs_to.resource
controller.send :belongs_to, target, options.dup
end
def belongs_to_config
@belongs_to
end
def belongs_to_param
if belongs_to? && belongs_to_config.required?
belongs_to_config.to_param
end
end
# Do we belong to another resource?
def belongs_to?
!!belongs_to_config
end
# The csv builder for this resource
def csv_builder
@csv_builder || default_csv_builder
end
def breadcrumb
instance_variable_defined?(:@breadcrumb) ? @breadcrumb : namespace.breadcrumb
end
def order_clause
@order_clause || namespace.order_clause
end
def create_another
instance_variable_defined?(:@create_another) ? @create_another : namespace.create_another
end
def find_resource(id)
resource = resource_class.public_send(*method_for_find(id))
(decorator_class && resource) ? decorator_class.new(resource) : resource
end
def resource_columns
resource_attributes.values
end
def resource_attributes
@resource_attributes ||= default_attributes
end
def association_columns
@association_columns ||= resource_attributes.select { |key, value| key != value }.values
end
def content_columns
@content_columns ||= resource_attributes.select { |key, value| key == value }.values
end
private
def method_for_find(id)
if finder = resources_configuration[:self][:finder]
[finder, id]
else
[:find_by, { resource_class.primary_key => id }]
end
end
def default_csv_builder
@default_csv_builder ||= CSVBuilder.default_for_resource(self)
end
def define_resource_name_extension(resource)
Module.new do
define_method :model_name do
resource.resource_name
end
end
end
end # class Resource
end # module ActiveAdmin
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/component.rb | lib/active_admin/component.rb | # frozen_string_literal: true
module ActiveAdmin
class Component < Arbre::Component
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/menu_item.rb | lib/active_admin/menu_item.rb | # frozen_string_literal: true
require_relative "view_helpers/method_or_proc_helper"
module ActiveAdmin
class MenuItem
include Menu::MenuNode
include MethodOrProcHelper
attr_reader :html_options, :parent, :priority
# Builds a new menu item
#
# @param [Hash] options The options for the menu
#
# @option options [String, Symbol, Proc] :label
# The label to display for this menu item.
# Default: Titleized Resource Name
#
# @option options [String] :id
# A custom id to reference this menu item with.
# Default: underscored_resource_name
#
# @option options [String, Symbol, Proc] :url
# The URL this item will link to.
#
# @option options [Integer] :priority
# The lower the priority, the earlier in the menu the item will be displayed.
# Default: 10
#
# @option options [Symbol, Proc] :if
# This decides whether the menu item will be displayed. Evaluated on each request.
#
# @option options [Hash] :html_options
# A hash of options to pass to `link_to` when rendering the item
#
# @option [ActiveAdmin::MenuItem] :parent
# This menu item's parent. It will be displayed nested below its parent.
#
# NOTE: for :label, :url, and :if
# These options are evaluated in the view context at render time. Symbols are called
# as methods on `self`, and Procs are exec'd within `self`.
# Here are some examples of what you can do:
#
# menu if: :admin?
# menu url: :new_book_path
# menu url: :awesome_helper_you_defined
# menu label: ->{ User.some_method }
# menu label: ->{ I18n.t 'menus.user' }
#
def initialize(options = {})
super() # MenuNode
@label = options[:label]
@dirty_id = options[:id] || options[:label]
@url = options[:url] || "#"
@priority = options[:priority] || 10
@html_options = options[:html_options] || {}
@should_display = options[:if] || proc { true }
@parent = options[:parent]
yield(self) if block_given? # Builder style syntax
end
def id
@id ||= normalize_id @dirty_id
end
def label(context = nil)
render_in_context(context, @label)
end
def url(context = nil)
render_in_context(context, @url)
end
# Don't display if the :if option passed says so
# Don't display if the link isn't real, we have children, and none of the children are being displayed.
def display?(context = nil)
return false unless render_in_context(context, @should_display)
return false if !real_url?(context) && @children.any? && !items(context).any?
true
end
private
# URL is not nil, empty, or '#'
def real_url?(context = nil)
url = url context
url.present? && url != '#'
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/version.rb | lib/active_admin/version.rb | # frozen_string_literal: true
module ActiveAdmin
VERSION = "4.0.0.beta19"
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/menu.rb | lib/active_admin/menu.rb | # frozen_string_literal: true
module ActiveAdmin
# Each Namespace builds up it's own menu as the global navigation
#
# To build a new menu:
#
# menu = Menu.new do |m|
# m.add label: 'Dashboard', url: '/'
# m.add label: 'Users', url: '/users'
# end
#
# If you're interested in configuring a menu item, take a look at the
# options available in `ActiveAdmin::MenuItem`
#
class Menu
def initialize
super # MenuNode
yield(self) if block_given?
end
module MenuNode
def initialize
@children = {}
end
def [](id)
@children[normalize_id(id)]
end
def []=(id, child)
@children[normalize_id(id)] = child
end
# Recursively builds any given menu items. There are two syntaxes supported,
# as shown in the below examples. Both create an identical menu structure.
#
# Example 1:
# menu = Menu.new
# menu.add label: 'Dashboard' do |dash|
# dash.add label: 'My Child Dashboard'
# end
#
# Example 2:
# menu = Menu.new
# menu.add label: 'Dashboard'
# menu.add parent: 'Dashboard', label: 'My Child Dashboard'
#
def add(options)
options = options.dup # Make sure parameter is not modified
item = if parent = options.delete(:parent)
(self[parent] || add(label: parent)).add options
else
_add options.merge parent: self
end
yield(item) if block_given?
item
end
# Whether any children match the given item.
def include?(item)
@children.value?(item)
end
# Used in the UI to visually distinguish which menu item is selected.
def current?(item)
self == item || include?(item)
end
# Returns sorted array of menu items that should be displayed in this context.
# Sorts by priority first, then alphabetically by label if needed.
def items(context = nil)
@children.values.select { |i| i.display?(context) }.sort do |a, b|
result = a.priority <=> b.priority
result = a.label(context) <=> b.label(context) if result == 0
result
end
end
attr_reader :children
private
attr_writer :children
# The method that actually adds new menu items. Called by the public method.
# If this ID is already taken, transfer the children of the existing item to the new item.
def _add(options)
item = ActiveAdmin::MenuItem.new(options)
item.send :children=, self[item.id].children if self[item.id]
self[item.id] = item
end
def normalize_id(id)
case id
when String, Symbol, ActiveModel::Name
id.to_s.downcase.tr " ", "_"
when ActiveAdmin::Resource::Name
id.param_key
else
raise TypeError, "#{id.class} isn't supported as a Menu ID"
end
end
end
include MenuNode
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/menu_collection.rb | lib/active_admin/menu_collection.rb | # frozen_string_literal: true
module ActiveAdmin
DEFAULT_MENU = :default
# A MenuCollection stores multiple menus for any given namespace. Namespaces delegate
# the addition of menu items to this class.
class MenuCollection
def initialize
@menus = {}
@build_callbacks = []
@built = false
end
# Add a new menu item to a menu in the collection
def add(menu_name, menu_item_options = {})
menu = find_or_create(menu_name)
menu.add menu_item_options
end
def clear!
@menus = {}
@built = false
end
def exists?(menu_name)
@menus.key?(menu_name)
end
def fetch(menu_name)
build_menus!
@menus[menu_name] or
raise NoMenuError, "No menu by the name of #{menu_name.inspect} in available menus: #{@menus.keys.join(", ")}"
end
# Add callbacks that will be run when the menu is going to be built. This
# helps use with reloading and allows configurations to add items to menus.
#
# @param [Proc] block A block which will be ran when the menu is built. The
# will have the menu collection yielded.
def on_build(&block)
@build_callbacks << block
end
# Add callbacks that will be run before the menu is built
def before_build(&block)
@build_callbacks.unshift(block)
end
def menu(menu_name)
menu = find_or_create(menu_name)
yield(menu) if block_given?
menu
end
private
def built?
@built
end
def build_menus!
return if built?
build_default_menu
run_on_build_callbacks
@built = true
end
def run_on_build_callbacks
@build_callbacks.each do |callback|
callback.call(self)
end
end
def build_default_menu
find_or_create DEFAULT_MENU
end
def find_or_create(menu_name)
menu_name ||= DEFAULT_MENU
@menus[menu_name] ||= ActiveAdmin::Menu.new
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/application.rb | lib/active_admin/application.rb | # frozen_string_literal: true
require_relative "router"
require_relative "application_settings"
require_relative "namespace_settings"
module ActiveAdmin
class Application
class << self
def setting(name, default)
ApplicationSettings.register name, default
end
def inheritable_setting(name, default)
NamespaceSettings.register name, default
end
end
def settings
@settings ||= SettingsNode.build(ApplicationSettings)
end
def namespace_settings
@namespace_settings ||= SettingsNode.build(NamespaceSettings)
end
def respond_to_missing?(method, include_private = false)
[settings, namespace_settings].any? { |sets| sets.respond_to?(method) } || super
end
def method_missing(method, *args)
if settings.respond_to?(method)
settings.send(method, *args)
elsif namespace_settings.respond_to?(method)
namespace_settings.send(method, *args)
else
super
end
end
attr_reader :namespaces
def initialize
@namespaces = Namespace::Store.new
end
# Event that gets triggered on load of Active Admin
BeforeLoadEvent = "active_admin.application.before_load".freeze
AfterLoadEvent = "active_admin.application.after_load".freeze
# Runs before the app's AA initializer
def setup!
end
# Runs after the app's AA initializer
def prepare!
remove_active_admin_load_paths_from_rails_autoload_and_eager_load
attach_reloader
end
# Registers a brand new configuration for the given resource.
def register(resource, options = {}, &block)
ns = options.fetch(:namespace) { default_namespace }
namespace(ns).register resource, options, &block
end
# Creates a namespace for the given name
#
# Yields the namespace if a block is given
#
# @return [Namespace] the new or existing namespace
def namespace(name)
name ||= :root
namespace = namespaces[name.to_sym] ||= begin
namespace = Namespace.new(self, name)
ActiveSupport::Notifications.instrument ActiveAdmin::Namespace::RegisterEvent, { active_admin_namespace: namespace }
namespace
end
yield(namespace) if block_given?
namespace
end
# Register a page
#
# @param name [String] The page name
# @option [Hash] Accepts option :namespace.
# @&block The registration block.
#
def register_page(name, options = {}, &block)
ns = options.fetch(:namespace) { default_namespace }
namespace(ns).register_page name, options, &block
end
# Whether all configuration files have been loaded
def loaded?
@@loaded ||= false
end
# Removes all defined controllers from memory. Useful in
# development, where they are reloaded on each request.
def unload!
namespaces.each(&:unload!)
@@loaded = false
end
# Loads all ruby files that are within the load_paths setting.
# To reload everything simply call `ActiveAdmin.unload!`
def load!
unless loaded?
ActiveSupport::Notifications.instrument BeforeLoadEvent, { active_admin_application: self } # before_load hook
files.each { |file| load file } # load files
namespace(default_namespace) # init AA resources
ActiveSupport::Notifications.instrument AfterLoadEvent, { active_admin_application: self } # after_load hook
@@loaded = true
end
end
def load(file)
DatabaseHitDuringLoad.capture { super }
end
# Returns ALL the files to be loaded
def files
load_paths.flatten.compact.uniq.flat_map { |path| Dir["#{path}/**/*.rb"].sort }
end
# Creates all the necessary routes for the ActiveAdmin configurations
#
# Use this within the routes.rb file:
#
# Application.routes.draw do |map|
# ActiveAdmin.routes(self)
# end
#
# @param rails_router [ActionDispatch::Routing::Mapper]
def routes(rails_router)
load!
Router.new(router: rails_router, namespaces: namespaces).apply
end
# Adds before, around and after filters to all controllers.
# Example usage:
# ActiveAdmin.before_action :authenticate_admin!
#
AbstractController::Callbacks::ClassMethods.public_instance_methods.
select { |m| m.end_with?('_action') }.each do |name|
define_method name do |*args, &block|
ActiveSupport.on_load(:active_admin_controller) do
public_send name, *args, &block
end
end
end
def controllers_for_filters
controllers = [BaseController]
controllers.push(*Devise.controllers_for_filters) if Dependency.devise?
controllers
end
private
# Since app/admin is alphabetically before app/models, we have to remove it
# from the host app's +autoload_paths+ to prevent missing constant errors.
#
# As well, we have to remove it from +eager_load_paths+ to prevent the
# files from being loaded twice in production.
def remove_active_admin_load_paths_from_rails_autoload_and_eager_load
ActiveSupport::Dependencies.autoload_paths -= load_paths
Rails.application.config.eager_load_paths -= load_paths
end
# Hook into the Rails code reloading mechanism so that things are reloaded
# properly in development mode.
#
# If any of the app files (e.g. models) has changed, we need to reload all
# the admin files. If the admin files themselves has changed, we need to
# regenerate the routes as well.
def attach_reloader
Rails.application.config.after_initialize do |app|
unload_active_admin = -> { ActiveAdmin.application.unload! }
if app.config.reload_classes_only_on_change
# Rails is about to unload all the app files (e.g. models), so we
# should first unload the classes generated by Active Admin, otherwise
# they will contain references to the stale (unloaded) classes.
ActiveSupport::Reloader.to_prepare(prepend: true, &unload_active_admin)
else
# If the user has configured the app to always reload app files after
# each request, so we should unload the generated classes too.
ActiveSupport::Reloader.to_complete(&unload_active_admin)
end
admin_dirs = {}
load_paths.each do |path|
admin_dirs[path] = [:rb]
end
routes_reloader = app.config.file_watcher.new([], admin_dirs) do
app.reload_routes!
end
app.reloaders << routes_reloader
ActiveSupport::Reloader.to_prepare do
# Rails might have reloaded the routes for other reasons (e.g.
# routes.rb has changed), in which case Active Admin would have been
# loaded via the `ActiveAdmin.routes` call in `routes.rb`.
#
# Otherwise, we should check if any of the admin files are changed
# and force the routes to reload if necessary. This would again causes
# Active Admin to load via `ActiveAdmin.routes`.
#
# Finally, if Active Admin is still not loaded at this point, then we
# would need to load it manually.
unless ActiveAdmin.application.loaded?
routes_reloader.execute_if_updated
ActiveAdmin.application.load!
end
end
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/collection_decorator.rb | lib/active_admin/collection_decorator.rb | # frozen_string_literal: true
module ActiveAdmin
# This class decorates a collection of objects delegating
# methods to behave like an Array. It's used to decouple ActiveAdmin
# from Draper and thus being able to use PORO decorators as well.
#
# It's implementation is heavily based on the Draper::CollectionDecorator
# https://github.com/drapergem/draper/blob/aaa06bd2f1e219838b241a5534e7ca513edd1fe2/lib/draper/collection_decorator.rb
class CollectionDecorator
# @return the collection being decorated.
attr_reader :object
# @return [Class] the decorator class used to decorate each item, as set by {#initialize}.
attr_reader :decorator_class
array_methods = Array.instance_methods - Object.instance_methods
delegate :==, :as_json, *array_methods, to: :decorated_collection
def initialize(object, with:)
@object = object
@decorator_class = with
end
class << self
alias_method :decorate, :new
end
def decorated_collection
@decorated_collection ||= object.map { |item| decorator_class.new(item) }
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/application_settings.rb | lib/active_admin/application_settings.rb | # frozen_string_literal: true
require_relative "settings_node"
module ActiveAdmin
class ApplicationSettings < SettingsNode
# The default namespace to put controllers and routes inside. Set this
# in config/initializers/active_admin.rb using:
#
# config.default_namespace = :super_admin
#
register :default_namespace, :admin
register :app_path, Rails.root
# Load paths for admin configurations. Add folders to this load path
# to load up other resources for administration. External gems can
# include their paths in this load path to provide active_admin UIs
register :load_paths, [File.expand_path("app/admin", Rails.root)]
# Set default localize format for Date/Time values
register :localize_format, :long
# Active Admin makes educated guesses when displaying objects, this is
# the list of methods it tries calling in order
# Note that Formtastic also has 'collection_label_methods' similar to this
# used by auto generated dropdowns in filter or belongs_to field of Active Admin
register :display_name_methods, [ :display_name,
:full_name,
:name,
:username,
:login,
:title,
:email,
:to_s ]
# To make debugging easier, by default don't stream in development
register :disable_streaming_in, ["development"]
# Remove sensitive attributes from being displayed, made editable, or exported by default
register :filter_attributes, [:encrypted_password, :password, :password_confirmation]
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/dynamic_settings_node.rb | lib/active_admin/dynamic_settings_node.rb | # frozen_string_literal: true
require_relative "dynamic_setting"
require_relative "settings_node"
module ActiveAdmin
class DynamicSettingsNode < SettingsNode
class << self
def register(name, value, type = nil)
class_attribute "#{name}_setting"
add_reader(name)
add_writer(name, type)
send :"#{name}=", value
end
def add_reader(name)
define_singleton_method(name) do |*args|
send(:"#{name}_setting").value(*args)
end
end
def add_writer(name, type)
define_singleton_method(:"#{name}=") do |value|
send(:"#{name}_setting=", DynamicSetting.build(value, type))
end
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/authorization_adapter.rb | lib/active_admin/authorization_adapter.rb | # frozen_string_literal: true
module ActiveAdmin
# Default Authorization permissions for Active Admin
module Authorization
READ = :read
NEW = :new
CREATE = :create
EDIT = :edit
UPDATE = :update
DESTROY = :destroy
end
Auth = Authorization
# Active Admin's default authorization adapter. This adapter returns true
# for all requests to `#authorized?`. It should be the starting point for
# implementing your own authorization adapter.
#
# To view an example subclass, check out `ActiveAdmin::CanCanAdapter`
class AuthorizationAdapter
attr_reader :resource, :user
# Initialize a new authorization adapter. This happens on each and
# every request to a controller.
#
# @param [ActiveAdmin::Resource, ActiveAdmin::Page] resource The resource
# that the user is currently on. Note, we may be authorizing access
# to a different subject, so don't rely on this other than to
# pull configuration information from.
#
# @param [any] user The current user. The user is set to whatever is returned
# from `#current_active_admin_user` in the controller.
#
def initialize(resource, user)
@resource = resource
@user = user
end
# Returns true of false depending on if the user is authorized to perform
# the action on the subject.
#
# @param [Symbol] action The name of the action to perform. Usually this will be
# one of the `ActiveAdmin::Auth::*` symbols.
#
# @param [any] subject The subject the action is being performed on usually this
# is a model object. Note, that this is NOT always in instance, it can be
# the class of the subject also. For example, Active Admin uses the class
# of the resource to decide if the resource should be displayed in the
# global navigation. To deal with this nicely in a case statement, take
# a look at `#normalized(klass)`
#
# @return [Boolean]
def authorized?(action, subject = nil)
true
end
# A hook method for authorization libraries to scope the collection. By
# default, we just return the same collection. The returned scope is used
# as the starting point for all queries to the db in the controller.
#
# @param [ActiveRecord::Relation] collection The collection the user is
# attempting to view.
#
# @param [Symbol] action The name of the action to perform. Usually this will be
# one of the `ActiveAdmin::Auth::*` symbols. Defaults to `Auth::READ` if
# no action passed in.
#
# @return [ActiveRecord::Relation] A new collection, scoped to the
# objects that the current user has access to.
def scope_collection(collection, action = Auth::READ)
collection
end
private
# The `#authorized?` method's subject can be set to both instances as well
# as classes of objects. This can make it much difficult to create simple
# case statements for authorization since you have to handle both the
# class level match and the instance level match.
#
# For example:
#
# class MyAuthAdapter < ActiveAdmin::AuthorizationAdapter
#
# def authorized?(action, subject = nil)
# case subject
# when Post
# true
# when Class
# if subject == Post
# true
# end
# end
# end
#
# end
#
# To handle this, the normalized method takes care of returning a object
# which implements `===` to be matched in a case statement.
#
# The above now becomes:
#
# class MyAuthAdapter < ActiveAdmin::AuthorizationAdapter
#
# def authorized?(action, subject = nil)
# case subject
# when normalized(Post)
# true
# end
# end
#
# end
def normalized(klass)
NormalizedMatcher.new(klass)
end
class NormalizedMatcher
def initialize(klass)
@klass = klass
end
def ===(other)
@klass == other || other.is_a?(@klass)
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/view_helpers.rb | lib/active_admin/view_helpers.rb | # frozen_string_literal: true
module ActiveAdmin
module ViewHelpers
# Require all ruby files in the view helpers dir
Dir[File.expand_path("view_helpers", __dir__) + "/*.rb"].each { |f| require f }
include MethodOrProcHelper
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/devise.rb | lib/active_admin/devise.rb | # frozen_string_literal: true
ActiveAdmin::Dependency.devise! ActiveAdmin::Dependency::Requirements::DEVISE
require "devise"
module ActiveAdmin
module Devise
def self.config
{
path: ActiveAdmin.application.default_namespace || "/",
controllers: ActiveAdmin::Devise.controllers,
path_names: { sign_in: "login", sign_out: "logout" }
}
end
def self.controllers
{
sessions: "active_admin/devise/sessions",
passwords: "active_admin/devise/passwords",
unlocks: "active_admin/devise/unlocks",
registrations: "active_admin/devise/registrations",
confirmations: "active_admin/devise/confirmations"
}
end
module Controller
extend ::ActiveSupport::Concern
included do
layout "active_admin_logged_out"
helper ::ActiveAdmin::LayoutHelper
helper ::ActiveAdmin::FormHelper
end
# Redirect to the default namespace on logout
def root_path
namespace = ActiveAdmin.application.default_namespace.presence
root_path_method = [namespace, :root_path].compact.join("_")
path = if Helpers::Routes.respond_to? root_path_method
Helpers::Routes.send root_path_method
else
# Guess a root_path when url_helpers not helpful
"/#{namespace}"
end
# NOTE: `relative_url_root` is deprecated by Rails.
# Remove prefix here if it is removed completely.
prefix = Rails.configuration.action_controller[:relative_url_root] || ""
prefix + path
end
end
class SessionsController < ::Devise::SessionsController
include ::ActiveAdmin::Devise::Controller
ActiveSupport.run_load_hooks(:active_admin_controller, self)
end
class PasswordsController < ::Devise::PasswordsController
include ::ActiveAdmin::Devise::Controller
ActiveSupport.run_load_hooks(:active_admin_controller, self)
end
class UnlocksController < ::Devise::UnlocksController
include ::ActiveAdmin::Devise::Controller
ActiveSupport.run_load_hooks(:active_admin_controller, self)
end
class RegistrationsController < ::Devise::RegistrationsController
include ::ActiveAdmin::Devise::Controller
ActiveSupport.run_load_hooks(:active_admin_controller, self)
end
class ConfirmationsController < ::Devise::ConfirmationsController
include ::ActiveAdmin::Devise::Controller
ActiveSupport.run_load_hooks(:active_admin_controller, self)
end
def self.controllers_for_filters
[SessionsController, PasswordsController, UnlocksController,
RegistrationsController, ConfirmationsController
]
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/page.rb | lib/active_admin/page.rb | # frozen_string_literal: true
module ActiveAdmin
# Page is the primary data storage for page configuration in Active Admin
#
# When you register a page (ActiveAdmin.register_page "Status") you are actually creating
# a new Page instance within the given Namespace.
#
# The instance of the current page is available in PageController and views
# by calling the #active_admin_config method.
#
class Page
# The namespace this config belongs to
attr_reader :namespace
# The name of the page
attr_reader :name
# An array of custom actions defined for this page
attr_reader :page_actions
# Set breadcrumb builder
attr_accessor :breadcrumb
module Base
def initialize(namespace, name, options)
@namespace = namespace
@name = name
@options = options
@page_actions = []
end
end
include Base
include Resource::Controllers
include Resource::PagePresenters
include Resource::Sidebars
include Resource::ActionItems
include Resource::Menu
include Resource::Naming
include Resource::Routes
# label is singular
def plural_resource_label
name
end
def resource_name
@resource_name ||= Resource::Name.new(nil, name)
end
def underscored_resource_name
resource_name.to_s.parameterize.underscore
end
def camelized_resource_name
underscored_resource_name.camelize
end
def namespace_name
namespace.name.to_s
end
def default_menu_options
super.merge(id: resource_name)
end
def controller_name
[namespace.module_name, camelized_resource_name + "Controller"].compact.join("::")
end
# Override from `ActiveAdmin::Resource::Controllers`
def route_uncountable?
false
end
def add_default_action_items
end
def add_default_sidebar_sections
end
# Clears all the custom actions this page knows about
def clear_page_actions!
@page_actions = []
end
def belongs_to(target, options = {})
@belongs_to = Resource::BelongsTo.new(self, target, options)
self.navigation_menu_name = target unless @belongs_to.optional?
controller.send :belongs_to, target, options.dup
end
def belongs_to_config
@belongs_to
end
# Do we belong to another resource?
def belongs_to?
!!belongs_to_config
end
def breadcrumb
instance_variable_defined?(:@breadcrumb) ? @breadcrumb : namespace.breadcrumb
end
def order_clause
@order_clause || namespace.order_clause
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/namespace.rb | lib/active_admin/namespace.rb | # frozen_string_literal: true
require_relative "resource_collection"
module ActiveAdmin
# Namespaces are the basic organizing principle for resources within Active Admin
#
# Each resource is registered into a namespace which defines:
# * the namespaceing for routing
# * the module to namespace controllers
# * the menu which gets displayed (other resources in the same namespace)
#
# For example:
#
# ActiveAdmin.register Post, namespace: :admin
#
# Will register the Post model into the "admin" namespace. This will namespace the
# urls for the resource to "/admin/posts" and will set the controller to
# Admin::PostsController
#
# You can also register to the "root" namespace, which is to say no namespace at all.
#
# ActiveAdmin.register Post, namespace: false
#
# This will register the resource to an instantiated namespace called :root. The
# resource will be accessible from "/posts" and the controller will be PostsController.
#
class Namespace
class << self
def setting(name, default)
ActiveAdmin.deprecator.warn "This method does not do anything and will be removed."
end
end
RegisterEvent = "active_admin.namespace.register".freeze
attr_reader :application, :resources, :menus
def initialize(application, name)
@application = application
@name = name.to_s.underscore
@resources = ResourceCollection.new
register_module unless root?
build_menu_collection
end
def name
@name.to_sym
end
def settings
@settings ||= SettingsNode.build(application.namespace_settings)
end
def respond_to_missing?(method, include_private = false)
settings.respond_to?(method) || super
end
def method_missing(method, *args)
settings.respond_to?(method) ? settings.send(method, *args) : super
end
# Register a resource into this namespace. The preferred method to access this is to
# use the global registration ActiveAdmin.register which delegates to the proper
# namespace instance.
def register(resource_class, options = {}, &block)
config = find_or_build_resource(resource_class, options)
# Register the resource
register_resource_controller(config)
parse_registration_block(config, &block) if block
reset_menu!
# Dispatch a registration event
ActiveSupport::Notifications.instrument ActiveAdmin::Resource::RegisterEvent, { active_admin_resource: config }
# Return the config
config
end
def register_page(name, options = {}, &block)
config = build_page(name, options)
# Register the resource
register_page_controller(config)
parse_page_registration_block(config, &block) if block
reset_menu!
config
end
def root?
name == :root
end
# Returns the name of the module if required. Will be nil if none
# is required.
#
# eg:
# Namespace.new(:admin).module_name # => 'Admin'
# Namespace.new(:root).module_name # => nil
#
def module_name
root? ? nil : @name.camelize
end
def route_prefix
root? ? nil : @name
end
# Unload all the registered resources for this namespace
def unload!
unload_resources!
reset_menu!
end
# Returns the first registered ActiveAdmin::Resource instance for a given class
def resource_for(klass)
resources[klass]
end
def fetch_menu(name)
@menus.fetch(name)
end
def reset_menu!
@menus.clear!
end
# Add a callback to be ran when we build the menu
#
# @param [Symbol] name The name of the menu. Default: :default
# @yield [ActiveAdmin::Menu] The block to be ran when the menu is built
#
# @return [void]
def build_menu(name = DEFAULT_MENU)
@menus.before_build do |menus|
menus.menu name do |menu|
yield menu
end
end
end
protected
def build_menu_collection
@menus = MenuCollection.new
@menus.on_build do
resources.each do |resource|
resource.add_to_menu(@menus)
end
end
end
# Either returns an existing Resource instance or builds a new one.
def find_or_build_resource(resource_class, options)
resources.add Resource.new(self, resource_class, options)
end
def build_page(name, options)
resources.add Page.new(self, name, options)
end
# TODO: replace `eval` with `Class.new`
def register_page_controller(config)
eval "class ::#{config.controller_name} < ActiveAdmin::PageController; end"
config.controller.active_admin_config = config
end
def unload_resources!
resources.each do |resource|
parent = (module_name || "Object").constantize
name = resource.controller_name.split("::").last
parent.send(:remove_const, name) if parent.const_defined?(name, false)
# Remove circular references
resource.controller.active_admin_config = nil
if resource.is_a?(Resource) && resource.dsl
resource.dsl.run_registration_block { @config = nil }
end
end
@resources = ResourceCollection.new
end
# Creates a ruby module to namespace all the classes in if required
def register_module
unless Object.const_defined? module_name
Object.const_set module_name, Module.new
end
end
# TODO: replace `eval` with `Class.new`
def register_resource_controller(config)
eval "class ::#{config.controller_name} < ActiveAdmin::ResourceController; end"
config.controller.active_admin_config = config
end
def parse_registration_block(config, &block)
config.dsl = ResourceDSL.new(config)
config.dsl.run_registration_block(&block)
end
def parse_page_registration_block(config, &block)
PageDSL.new(config).run_registration_block(&block)
end
class Store
include Enumerable
delegate :[], :[]=, :empty?, to: :@namespaces
def initialize
@namespaces = {}
end
def each(&block)
@namespaces.values.each(&block)
end
def names
@namespaces.keys
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/views.rb | lib/active_admin/views.rb | # frozen_string_literal: true
module ActiveAdmin
module Views
# Loads all the classes in views/*.rb
Dir[File.expand_path("views", __dir__) + "/**/*.rb"].sort.each { |f| require f }
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/router.rb | lib/active_admin/router.rb | # frozen_string_literal: true
module ActiveAdmin
# @private
class Router
attr_reader :namespaces, :router
def initialize(router:, namespaces:)
@router = router
@namespaces = namespaces
end
def apply
define_root_routes
define_resources_routes
end
private
def define_root_routes
namespaces.each do |namespace|
if namespace.root?
router.root namespace.root_to_options.merge(to: namespace.root_to)
else
router.namespace namespace.name, **namespace.route_options.dup do
router.root namespace.root_to_options.merge(to: namespace.root_to, as: :root)
end
end
end
end
# Defines the routes for each resource
def define_resources_routes
resources = namespaces.flat_map { |n| n.resources.values }
resources.each do |config|
define_resource_routes(config)
end
end
def define_resource_routes(config)
if config.namespace.root?
define_routes(config)
else
# Add on the namespace if required
define_namespace(config)
end
end
def define_routes(config)
if config.belongs_to?
define_belongs_to_routes(config)
else
page_or_resource_routes(config)
end
end
def page_or_resource_routes(config)
config.is_a?(Page) ? page_routes(config) : resource_routes(config)
end
def resource_routes(config)
router.resources config.resource_name.route_key, only: config.defined_actions do
define_actions(config)
end
end
def page_routes(config)
page = config.underscored_resource_name
router.get "/#{page}", to: "#{page}#index"
config.page_actions.each do |action|
Array.wrap(action.http_verb).each do |verb|
build_route(verb, "/#{page}/#{action.name}" => "#{page}##{action.name}")
end
end
end
# Defines member and collection actions
def define_actions(config)
router.member do
config.member_actions.each { |action| build_action(action) }
end
router.collection do
config.collection_actions.each { |action| build_action(action) }
router.post :batch_action if config.batch_actions_enabled?
end
end
# Deals with +ControllerAction+ instances
# Builds one route for each HTTP verb passed in
def build_action(action)
build_route(action.http_verb, action.name)
end
def build_route(verbs, ...)
Array.wrap(verbs).each { |verb| router.send(verb, ...) }
end
def define_belongs_to_routes(config)
# If it's optional, make the normal resource routes
page_or_resource_routes(config) if config.belongs_to_config.optional?
# Make the nested belongs_to routes
# :only is set to nothing so that we don't clobber any existing routes on the resource
router.resources config.belongs_to_config.target.resource_name.plural, only: [] do
page_or_resource_routes(config)
end
end
def define_namespace(config)
router.namespace config.namespace.name, **config.namespace.route_options.dup do
define_routes(config)
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/callbacks.rb | lib/active_admin/callbacks.rb | # frozen_string_literal: true
module ActiveAdmin
module Callbacks
extend ActiveSupport::Concern
CALLBACK_TYPES = %i[before after].freeze
private
# Simple callback system. Implements before and after callbacks for
# use within the controllers.
#
# We didn't use the ActiveSupport callbacks because they do not support
# passing in any arbitrary object into the callback method (which we
# need to do)
def run_callback(method, *args)
case method
when Symbol
send(method, *args)
when Proc
instance_exec(*args, &method)
else
raise "Please register with callbacks using a symbol or a block/proc."
end
end
module ClassMethods
private
# Define a new callback.
#
# Example:
#
# class MyClassWithCallbacks
# include ActiveAdmin::Callbacks
#
# define_active_admin_callbacks :save
#
# before_save do |arg1, arg2|
# # runs before save
# end
#
# after_save :call_after_save
#
# def save
# # Will run before, yield, then after
# run_save_callbacks :arg1, :arg2 do
# save!
# end
# end
#
# protected
#
# def call_after_save(arg1, arg2)
# # runs after save
# end
# end
#
def define_active_admin_callbacks(*names)
names.each do |name|
CALLBACK_TYPES.each do |type|
callback_name = "#{type}_#{name}_callbacks"
callback_ivar = "@#{callback_name}"
# def self.before_create_callbacks
singleton_class.send :define_method, callback_name do
instance_variable_get(callback_ivar) || instance_variable_set(callback_ivar, [])
end
singleton_class.send :private, callback_name
# def self.before_create
singleton_class.send :define_method, "#{type}_#{name}" do |method = nil, &block|
send(callback_name).push method || block
end
end
# def run_create_callbacks
define_method :"run_#{name}_callbacks" do |*args, &block|
self.class.send(:"before_#{name}_callbacks").each { |cbk| run_callback(cbk, *args) }
value = block.try :call
self.class.send(:"after_#{name}_callbacks").each { |cbk| run_callback(cbk, *args) }
return value
end
send :private, "run_#{name}_callbacks"
end
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/order_clause.rb | lib/active_admin/order_clause.rb | # frozen_string_literal: true
module ActiveAdmin
class OrderClause
attr_reader :field, :order, :active_admin_config
def initialize(active_admin_config, clause)
clause =~ /^([\w\.]+)(->'\w+')?_(desc|asc)$/
@column = $1
@op = $2
@order = $3
@active_admin_config = active_admin_config
@field = [@column, @op].compact.join
end
def valid?
@field.present? && @order.present?
end
def apply(chain)
chain.reorder(Arel.sql sql)
end
def to_sql
[table_column, @op, " ", @order].compact.join
end
def table
active_admin_config.resource_column_names.include?(@column) ? active_admin_config.resource_table_name : nil
end
def table_column
if (@column.include?('.'))
@column
else
[table, active_admin_config.resource_quoted_column_name(@column)].compact.join(".")
end
end
def sql
custom_sql || to_sql
end
protected
def custom_sql
if active_admin_config.ordering[@column].present?
active_admin_config.ordering[@column].call(self)
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/localizers.rb | lib/active_admin/localizers.rb | # frozen_string_literal: true
require_relative "localizers/resource_localizer"
module ActiveAdmin
module Localizers
class << self
def resource(active_admin_config)
ResourceLocalizer.from_resource(active_admin_config)
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/page_presenter.rb | lib/active_admin/page_presenter.rb | # frozen_string_literal: true
module ActiveAdmin
# A simple object that gets used to present different aspects of views
#
# Initialize with a set of options and a block. The options become
# available using hash style syntax.
#
# Usage:
#
# presenter = PagePresenter.new as: :table do
# # some awesome stuff
# end
#
# presenter[:as] #=> :table
# presenter.block #=> The block passed in to new
#
class PagePresenter
attr_reader :block, :options
delegate :has_key?, :fetch, to: :options
def initialize(options = {}, &block)
@options = options
@block = block
end
def [](key)
@options[key]
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/settings_node.rb | lib/active_admin/settings_node.rb | # frozen_string_literal: true
module ActiveAdmin
class SettingsNode
class << self
# Never instantiated. Variables are stored in the singleton_class.
private_class_method :new
# @return anonymous class with same accessors as the superclass.
def build(superclass = self)
Class.new(superclass)
end
def register(name, value)
class_attribute name
send :"#{name}=", value
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/resource_collection.rb | lib/active_admin/resource_collection.rb | # frozen_string_literal: true
module ActiveAdmin
# This is a container for resources, which acts much like a Hash.
# It's assumed that an added resource responds to `resource_name`.
class ResourceCollection
include Enumerable
extend Forwardable
def_delegators :@collection, :empty?, :has_key?, :keys, :values, :size
def initialize
@collection = {}
end
def add(resource)
if match = @collection[resource.resource_name]
raise_if_mismatched! match, resource
match
else
@collection[resource.resource_name] = resource
end
end
# Changes `each` to pass in the value, instead of both the key and value.
def each(&block)
values.each(&block)
end
def [](obj)
@collection[obj] || find_resource(obj)
end
private
# Finds a resource based on the resource name, resource class, or base class.
def find_resource(obj)
resources.detect do |r|
r.resource_name.to_s == obj.to_s
end || resources.detect do |r|
r.resource_class.to_s == obj.to_s
end ||
if obj.respond_to? :base_class
resources.detect { |r| r.resource_class.to_s == obj.base_class.to_s }
end
end
def resources
select { |r| r.class <= Resource } # can otherwise be a Page
end
def raise_if_mismatched!(existing, given)
if existing.class != given.class
raise IncorrectClass.new existing, given
elsif given.class <= Resource && existing.resource_class != given.resource_class
raise ConfigMismatch.new existing, given
end
end
class IncorrectClass < StandardError
def initialize(existing, given)
super "You're trying to register #{given.resource_name} which is a #{given.class}, " +
"but #{existing.resource_name}, a #{existing.class} has already claimed that name."
end
end
class ConfigMismatch < StandardError
def initialize(existing, given)
super "You're trying to register #{given.resource_class} as #{given.resource_name}, " +
"but the existing #{existing.class} config was built for #{existing.resource_class}!"
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/dsl.rb | lib/active_admin/dsl.rb | # frozen_string_literal: true
module ActiveAdmin
# The Active Admin DSL. This class is where all the registration blocks
# are evaluated. This is the central place for the API given to
# users of Active Admin.
#
class DSL
def initialize(config)
@config = config
end
# Runs the registration block inside this object
def run_registration_block(&block)
instance_exec(&block) if block
end
# The instance of ActiveAdmin::Resource that's being registered
# currently. You can use this within your registration blocks to
# modify options:
#
# eg:
#
# ActiveAdmin.register Post do
# config.sort_order = "id_desc"
# end
#
def config
@config
end
# Include a module with this resource. The modules' `included` method
# is called with the instance of the `ActiveAdmin::DSL` passed into it.
#
# eg:
#
# module HelpSidebar
#
# def self.included(dsl)
# dsl.sidebar "Help" do
# "Call us for Help"
# end
# end
#
# end
#
# ActiveAdmin.register Post do
# include HelpSidebar
# end
#
# @param [Module] mod A module to include
#
# @return [Nil]
def include(mod)
mod.included(self)
end
# Returns the controller for this resource. If you pass a
# block, it will be evaluated in the controller.
#
# Example:
#
# ActiveAdmin.register Post do
#
# controller do
# def some_method_on_controller
# # Method gets added to Admin::PostsController
# end
# end
#
# end
#
def controller(&block)
@config.controller.class_exec(&block) if block
@config.controller
end
# Add a new action item to the resource
#
# @param [Symbol] name
# @param [Hash] options valid keys include:
# :only: A single or array of controller actions to display
# this action item on.
# :except: A single or array of controller actions not to
# display this action item on.
def action_item(name, options = {}, &block)
config.add_action_item(name, options, &block)
end
# Add a new batch action item to the resource
# Provide a symbol/string to register the action, options, & block to execute on request
#
# To unregister an existing action, just provide the symbol & pass false as the second param
#
# @param [Symbol or String] title
# @param [Hash] options valid keys include:
# => :if is a proc that will be called to determine if the BatchAction should be displayed
# => :sort_order is used to sort the batch actions ascending
# => :confirm is a string which the user will have to accept in order to process the action
#
def batch_action(title, options = {}, &block)
# Create symbol & title information
if title.is_a? String
sym = title.titleize.tr(" ", "").underscore.to_sym
else
sym = title
title = sym.to_s.titleize
end
# Either add/remove the batch action
unless options == false
config.add_batch_action(sym, title, options, &block)
else
config.remove_batch_action sym
end
end
# Set the options that are available for the item that will be placed in the global
# navigation of the menu.
def menu(options = {})
config.menu_item_options = options
end
# Set the name of the navigation menu to display. This is mainly used in conjunction with the
# `#belongs_to` functionality.
#
# @param [Symbol] menu_name The name of the menu to display as the global navigation
# when viewing this resource. Defaults to a menu named `:default`.
#
# Pass a block returning the name of a menu you want rendered for the request, being
# executed in the context of the controller
#
def navigation_menu(menu_name = nil, &block)
config.navigation_menu_name = menu_name || block
end
# Rewrite breadcrumb links.
# Block will be executed inside controller.
# Block must return an array if you want to rewrite breadcrumb links.
#
# Example:
# ActiveAdmin.register Post do
#
# breadcrumb do
# [
# link_to('my piece', '/my/link/to/piece')
# ]
# end
# end
#
def breadcrumb(&block)
config.breadcrumb = block
end
def sidebar(name, options = {}, &block)
config.sidebar_sections << ActiveAdmin::SidebarSection.new(name, options, &block)
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/batch_actions.rb | lib/active_admin/batch_actions.rb | # frozen_string_literal: true
ActiveAdmin.before_load do |app|
require_relative "batch_actions/resource_extension"
require_relative "batch_actions/controller"
# Add our Extensions
ActiveAdmin::Resource.send :include, ActiveAdmin::BatchActions::ResourceExtension
ActiveAdmin::ResourceController.send :include, ActiveAdmin::BatchActions::Controller
require_relative "batch_actions/views/batch_action_form"
require_relative "batch_actions/views/selection_cells"
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/scope.rb | lib/active_admin/scope.rb | # frozen_string_literal: true
module ActiveAdmin
class Scope
attr_reader :scope_method, :id, :scope_block, :display_if_block, :show_count, :default_block, :group
# Create a Scope
#
# Examples:
#
# Scope.new(:published)
# # => Scope with name 'Published' and scope method :published
#
# Scope.new('Published', :public)
# # => Scope with name 'Published' and scope method :public
#
# Scope.new(:published, show_count: :async)
# # => Scope with name 'Published' that queries its count asynchronously
#
# Scope.new(:published, show_count: false)
# # => Scope with name 'Published' that does not display a count
#
# Scope.new 'Published', :public, if: proc { current_admin_user.can? :manage, resource_class } do |articles|
# articles.where published: true
# end
# # => Scope with name 'Published' and scope method :public, optionally displaying the scope per the :if block
#
# Scope.new('Published') { |articles| articles.where(published: true) }
# # => Scope with name 'Published' using a block to scope
#
# Scope.new ->{Date.today.strftime '%A'}, :published_today
# # => Scope with dynamic title using the :published_today scope method
#
# Scope.new :published, nil, group: :status
# # => Scope with the group :status
#
def initialize(name, method = nil, options = {}, &block)
@name = name
@scope_method = method.try(:to_sym)
if name.is_a? Proc
raise "A string/symbol is required as the second argument if your label is a proc." unless method
@id = method.to_s.parameterize(separator: "_")
else
@scope_method ||= name.to_sym
@id = name.to_s.parameterize(separator: "_")
end
@scope_method = nil if @scope_method == :all
if block
@scope_method = nil
@scope_block = block
end
@localizer = options[:localizer]
@show_count = options.fetch(:show_count, true)
@display_if_block = options[:if] || proc { true }
@default_block = options[:default] || proc { false }
@group = options[:group].try(:to_sym)
end
def name
case @name
when String then @name
when Symbol then @localizer ? @localizer.t(@name, scope: "scopes") : @name.to_s.titleize
else @name
end
end
def async_count?
@show_count == :async
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/pundit_adapter.rb | lib/active_admin/pundit_adapter.rb | # frozen_string_literal: true
ActiveAdmin::Dependency.pundit!
require "pundit"
# Add a setting to the application to configure the pundit default policy
ActiveAdmin::Application.inheritable_setting :pundit_default_policy, nil
ActiveAdmin::Application.inheritable_setting :pundit_policy_namespace, nil
module ActiveAdmin
class PunditAdapter < AuthorizationAdapter
def authorized?(action, subject = nil)
policy = retrieve_policy(subject)
action = format_action(action, subject)
policy.respond_to?(action) && policy.public_send(action)
end
def scope_collection(collection, action = Auth::READ)
# scoping is applicable only to read/index action
# which means there is no way how to scope other actions
Pundit.policy_scope!(user, namespace(collection))
rescue Pundit::NotDefinedError => e
if default_policy_class&.const_defined?(:Scope)
default_policy_class::Scope.new(user, collection).resolve
else
raise e
end
end
def retrieve_policy(subject)
target = policy_target(subject)
if (policy = policy(namespace(target)) || compat_policy(subject))
policy
elsif default_policy_class
default_policy(subject)
else
raise Pundit::NotDefinedError, "unable to find a compatible policy for `#{target}`"
end
end
def format_action(action, subject)
# https://github.com/varvet/pundit/blob/main/lib/generators/pundit/install/templates/application_policy.rb
case action
when Auth::READ then subject.is_a?(Class) ? :index? : :show?
when Auth::DESTROY then subject.is_a?(Class) ? :destroy_all? : :destroy?
else "#{action}?"
end
end
private
def policy_target(subject)
case subject
when nil then resource
when Class then subject.new
else subject
end
end
# This method is needed to fallback to our previous policy searching logic.
# I.e.: when class name contains `default_policy_namespace` (eg: ShopAdmin)
# we should try to search it without namespace. This is because that's
# the only thing that worked in this case before we fixed our buggy namespace
# detection, so people are probably relying on it.
# This fallback might be removed in future versions of ActiveAdmin, so
# pundit_adapter search will work consistently with provided namespaces
def compat_policy(subject)
return unless default_policy_namespace
target = policy_target(subject)
return unless target.class.to_s.include?(default_policy_module) &&
(policy = policy(target))
policy_name = policy.class.to_s
ActiveAdmin.deprecator.warn "You have `pundit_policy_namespace` configured as `#{default_policy_namespace}`, " \
"but ActiveAdmin was unable to find policy #{default_policy_module}::#{policy_name}. " \
"#{policy_name} will be used instead. " \
"This behavior will be removed in future versions of ActiveAdmin. " \
"To fix this warning, move your #{policy_name} policy to the #{default_policy_module} namespace"
policy
end
def namespace(object)
if default_policy_namespace && !object.class.to_s.start_with?("#{default_policy_module}::")
[default_policy_namespace.to_sym, object]
else
object
end
end
def default_policy_class
ActiveAdmin.application.pundit_default_policy&.constantize
end
def default_policy(subject)
default_policy_class.new(user, subject)
end
def default_policy_namespace
ActiveAdmin.application.pundit_policy_namespace
end
def default_policy_module
default_policy_namespace.to_s.camelize
end
def policy(target)
policies[target] ||= Pundit.policy(user, target)
end
def policies
@policies ||= {}
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/async_count.rb | lib/active_admin/async_count.rb | # frozen_string_literal: true
module ActiveAdmin
class AsyncCount
class NotSupportedError < RuntimeError; end
def initialize(collection)
raise NotSupportedError, "#{collection.inspect} does not support :async_count" unless collection.respond_to?(:async_count)
@collection = collection.except(:select, :order)
@promise = @collection.async_count
end
def count
value = @promise.value
# value.value due to Rails bug https://github.com/rails/rails/issues/50776
value.respond_to?(:value) ? value.value : value
end
alias size count
delegate :except, :group_values, :length, :limit_value, to: :@collection
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/form_builder.rb | lib/active_admin/form_builder.rb | # frozen_string_literal: true
# Provides an intuitive way to build has_many associated records in the same form.
module Formtastic
module Inputs
module Base
def input_wrapping(&block)
html = super
template.concat(html) if template.output_buffer && template.assigns[:has_many_block]
html
end
end
end
end
module ActiveAdmin
class FormBuilder < ::Formtastic::FormBuilder
self.input_namespaces = [::Object, ::ActiveAdmin::Inputs, ::Formtastic::Inputs]
def cancel_link(url = { action: "index" }, html_options = {}, li_attrs = {})
li_attrs[:class] ||= "action cancel"
html_options[:class] ||= "cancel-link"
li_content = template.link_to I18n.t("active_admin.cancel"), url, html_options
template.content_tag(:li, li_content, li_attrs)
end
attr_accessor :already_in_an_inputs_block
def has_many(assoc, options = {}, &block)
HasManyBuilder.new(self, assoc, options).render(&block)
end
end
# Decorates a FormBuilder with the additional attributes and methods
# to build a has_many block. Nested has_many blocks are handled by
# nested decorators.
class HasManyBuilder < SimpleDelegator
attr_reader :assoc
attr_reader :options
attr_reader :heading, :sortable_column, :sortable_start
attr_reader :new_record, :destroy_option, :remove_record
def initialize(has_many_form, assoc, options)
super has_many_form
@assoc = assoc
@options = extract_custom_settings!(options.dup)
@options.reverse_merge!(for: assoc)
@options[:class] = [options[:class], "inputs has-many-fields"].compact.join(" ")
if sortable_column
@options[:for] = [assoc, sorted_children(sortable_column)]
end
end
def render(&block)
html = "".html_safe
html << template.content_tag(:h3, class: "has-many-fields-title") { heading } if heading.present?
html << template.capture { content_has_many(&block) }
html = wrap_div_or_li(html)
template.concat(html) if template.output_buffer
html
end
protected
# remove options that should not render as attributes
def extract_custom_settings!(options)
@heading = options.key?(:heading) ? options.delete(:heading) : default_heading
@sortable_column = options.delete(:sortable)
@sortable_start = options.delete(:sortable_start) || 0
@new_record = options.key?(:new_record) ? options.delete(:new_record) : true
@destroy_option = options.delete(:allow_destroy)
@remove_record = options.delete(:remove_record)
options
end
def default_heading
assoc_klass.model_name.human(count: 2.1)
end
def assoc_klass
@assoc_klass ||= __getobj__.object.class.reflect_on_association(assoc).klass
end
def content_has_many(&block)
form_block = proc do |form_builder|
render_has_many_form(form_builder, options[:parent], &block)
end
template.assigns[:has_many_block] = true
contents = without_wrapper { inputs(options, &form_block) }
contents ||= "".html_safe
js = new_record ? js_for_has_many(&form_block) : ""
contents << js
end
# Renders the Formtastic inputs then appends ActiveAdmin delete and sort actions.
def render_has_many_form(form_builder, parent, &block)
index = parent && form_builder.send(:parent_child_index, parent)
template.concat template.capture { yield(form_builder, index) }
template.concat has_many_actions(form_builder, "".html_safe)
end
def has_many_actions(form_builder, contents)
if form_builder.object.new_record?
contents << template.content_tag(:li, class: "input") do
remove_text = remove_record.is_a?(String) ? remove_record : I18n.t("active_admin.has_many_remove")
template.link_to remove_text, "#", class: "has-many-remove"
end
elsif allow_destroy?(form_builder.object)
form_builder.input(
:_destroy, as: :boolean,
wrapper_html: { class: "has-many-delete" },
label: I18n.t("active_admin.has_many_delete"))
end
if sortable_column
form_builder.input sortable_column, as: :hidden
# contents << template.content_tag(:li, class: "handle") do
# I18n.t("active_admin.move")
# end
end
contents
end
def allow_destroy?(form_object)
!! case destroy_option
when Symbol, String
form_object.public_send destroy_option
when Proc
destroy_option.call form_object
else
destroy_option
end
end
def sorted_children(column)
__getobj__.object.public_send(assoc).sort_by do |o|
attribute = o.public_send column
[attribute.nil? ? Float::INFINITY : attribute, o.id || Float::INFINITY]
end
end
def without_wrapper
is_being_wrapped = already_in_an_inputs_block
self.already_in_an_inputs_block = false
html = yield
self.already_in_an_inputs_block = is_being_wrapped
html
end
# Capture the ADD JS
def js_for_has_many(&form_block)
assoc_name = assoc_klass.model_name
placeholder = "NEW_#{assoc_name.to_s.underscore.upcase.tr('/', '_')}_RECORD"
opts = options.merge(
for: [assoc, assoc_klass.new],
for_options: { child_index: placeholder }
)
html = template.capture { __getobj__.send(:inputs_for_nested_attributes, opts, &form_block) }
text = new_record.is_a?(String) ? new_record : I18n.t("active_admin.has_many_new", model: assoc_name.human)
template.link_to text, "#", class: "has-many-add", data: {
html: CGI.escapeHTML(html).html_safe, placeholder: placeholder
}
end
def wrap_div_or_li(html)
template.content_tag(
already_in_an_inputs_block ? :li : :div,
html,
class: "has-many-container",
"data-has-many-association" => assoc,
"data-sortable" => sortable_column,
"data-sortable-start" => sortable_start)
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/dynamic_setting.rb | lib/active_admin/dynamic_setting.rb | # frozen_string_literal: true
module ActiveAdmin
class DynamicSetting
def self.build(setting, type)
(type ? klass(type) : self).new(setting)
end
def self.klass(type)
klass = "#{type.to_s.camelcase}Setting"
raise ArgumentError, "Unknown type: #{type}" unless ActiveAdmin.const_defined?(klass)
ActiveAdmin.const_get(klass)
end
def initialize(setting)
@setting = setting
end
def value(*_args)
@setting
end
end
# Many configuration options (Ex: site_title, title_image) could either be
# static (String), methods (Symbol) or procs (Proc). This wrapper takes care of
# returning the content when String or using instance_eval when Symbol or Proc.
#
class StringSymbolOrProcSetting < DynamicSetting
def value(context = self)
case @setting
when Symbol, Proc
context.instance_eval(&@setting)
else
@setting
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/controller_action.rb | lib/active_admin/controller_action.rb | # frozen_string_literal: true
module ActiveAdmin
class ControllerAction
attr_reader :name
def initialize(name, options = {})
@name = name
@options = options
end
def http_verb
@options[:method] ||= :get
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/namespace_settings.rb | lib/active_admin/namespace_settings.rb | # frozen_string_literal: true
require_relative "dynamic_settings_node"
module ActiveAdmin
class NamespaceSettings < DynamicSettingsNode
# The default number of resources to display on index pages
register :default_per_page, 30
# The max number of resources to display on index pages and batch exports
register :max_per_page, 10_000
# The title which gets displayed in the main layout
register :site_title, "", :string_symbol_or_proc
# The method to call in controllers to get the current user
register :current_user_method, false
# The method to call in the controllers to ensure that there
# is a currently authenticated admin user
register :authentication_method, false
# The path to log user's out with. If set to a symbol, we assume
# that it's a method to call which returns the path
register :logout_link_path, :destroy_admin_user_session_path
# Whether the batch actions are enabled or not
register :batch_actions, false
# Whether filters are enabled
register :filters, true
# The namespace root
register :root_to, "dashboard#index"
# Options that are passed to root_to
register :root_to_options, {}
# Options passed to the routes, i.e. { path: '/custom' }
register :route_options, {}
# Display breadcrumbs
register :breadcrumb, true
# Display create another checkbox on a new page
# @return [Boolean] (true)
register :create_another, false
# Default CSV options
register :csv_options, { col_sep: ",", byte_order_mark: "\xEF\xBB\xBF" }
# Default Download Links options
register :download_links, true
# The authorization adapter to use
register :authorization_adapter, ActiveAdmin::AuthorizationAdapter
# A proc to be used when a user is not authorized to view the current resource
register :on_unauthorized_access, :rescue_active_admin_access_denied
# Whether to display 'Current Filters' on search screen
register :current_filters, true
# class to handle ordering
register :order_clause, ActiveAdmin::OrderClause
# default show_count for scopes
register :scopes_show_count, true
# Request parameters that are permitted by default
register :permitted_params, [
:utf8, :_method, :authenticity_token, :commit, :id
]
# Set flash message keys that shouldn't show in ActiveAdmin.
# By default, we remove the `timedout` key from Devise.
register :flash_keys_to_except, ["timedout"]
# Include association filters by default
register :include_default_association_filters, true
register :maximum_association_filter_arity, :unlimited
register :filter_columns_for_large_association, [
:display_name,
:full_name,
:name,
:username,
:login,
:title,
:email,
]
register :filter_method_for_large_association, "_start"
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/filters.rb | lib/active_admin/filters.rb | # frozen_string_literal: true
require_relative "filters/dsl"
require_relative "filters/resource_extension"
require_relative "filters/formtastic_addons"
require_relative "filters/forms"
require_relative "helpers/optional_display"
# Add our Extensions
ActiveAdmin::ResourceDSL.send :include, ActiveAdmin::Filters::DSL
ActiveAdmin::Resource.send :include, ActiveAdmin::Filters::ResourceExtension
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/engine.rb | lib/active_admin/engine.rb | # frozen_string_literal: true
module ActiveAdmin
class Engine < ::Rails::Engine
isolate_namespace ActiveAdmin
# Set default values for app_path and load_paths before running initializers
initializer "active_admin.load_app_path", before: :load_config_initializers do |app|
ActiveAdmin::Application.setting :app_path, app.root
ActiveAdmin::Application.setting :load_paths, [File.expand_path("app/admin", app.root)]
end
initializer "active_admin.precompile", group: :all do |app|
if app.config.respond_to?(:assets)
app.config.assets.precompile += %w(active_admin.js active_admin.css active_admin_manifest.js)
end
end
initializer "active_admin.importmap", after: "importmap" do |app|
# Skip if importmap-rails is not installed
next unless app.config.respond_to?(:importmap)
ActiveAdmin.importmap.draw(Engine.root.join("config", "importmap.rb"))
package_path = Engine.root.join("app/javascript")
if app.config.respond_to?(:assets)
app.config.assets.paths << package_path
app.config.assets.paths << Engine.root.join("vendor/javascript")
end
if app.config.importmap.sweep_cache
ActiveAdmin.importmap.cache_sweeper(watches: package_path)
ActiveSupport.on_load(:action_controller_base) do
before_action { ActiveAdmin.importmap.cache_sweeper.execute_if_updated }
end
end
end
initializer "active_admin.routes" do
require_relative "helpers/routes/url_helpers"
end
initializer "active_admin.deprecator" do |app|
app.deprecators[:activeadmin] = ActiveAdmin.deprecator if app.respond_to?(:deprecators)
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/cancan_adapter.rb | lib/active_admin/cancan_adapter.rb | # frozen_string_literal: true
unless ActiveAdmin::Dependency.cancan? || ActiveAdmin::Dependency.cancancan?
ActiveAdmin::Dependency.cancan!
end
require "cancan"
# Add a setting to the application to configure the ability
ActiveAdmin::Application.inheritable_setting :cancan_ability_class, "Ability"
module ActiveAdmin
class CanCanAdapter < AuthorizationAdapter
def authorized?(action, subject = nil)
cancan_ability.can?(action, subject)
end
def cancan_ability
@cancan_ability ||= initialize_cancan_ability
end
def scope_collection(collection, action = ActiveAdmin::Auth::READ)
collection.accessible_by(cancan_ability, action)
end
private
def initialize_cancan_ability
klass = resource.namespace.cancan_ability_class
klass = klass.constantize if klass.is_a? String
klass.new user
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/resource_dsl.rb | lib/active_admin/resource_dsl.rb | # frozen_string_literal: true
module ActiveAdmin
# This is the class where all the register blocks are evaluated.
class ResourceDSL < DSL
private
# Redefine sort behaviour for column
#
# For example:
#
# # nulls last
# order_by(:age) do |order_clause|
# [order_clause.to_sql, 'NULLS LAST'].join(' ') if order_clause.order == 'desc'
# end
#
# # by last_name but in the case that there is no last name, by first_name.
# order_by(:full_name) do |order_clause|
# ['COALESCE(NULLIF(last_name, ''), first_name), first_name', order_clause.order].join(' ')
# end
#
#
def order_by(column, &block)
config.ordering[column] = block
end
def belongs_to(target, options = {})
config.belongs_to(target, options)
end
# Scope collection to a relation
def scope_to(*args, &block)
config.scope_to(*args, &block)
end
# Create a scope
def scope(*args, &block)
config.scope(*args, &block)
end
# Store relations that should be included
def includes(*args)
config.includes.push(*args)
end
#
# Keys included in the `permitted_params` setting are automatically whitelisted.
#
# Either
#
# permit_params :title, :author, :body, tags: []
#
# Or
#
# permit_params do
# defaults = [:title, :body]
# if current_user.admin?
# defaults + [:author]
# else
# defaults
# end
# end
#
def permit_params(*args, &block)
param_key = config.param_key.to_sym
controller do
define_method :permitted_params do
belongs_to_param = active_admin_config.belongs_to_param
create_another_param = :create_another if active_admin_config.create_another
permitted_params =
active_admin_namespace.permitted_params +
Array.wrap(belongs_to_param) +
Array.wrap(create_another_param)
params.permit(*permitted_params, param_key => block ? instance_exec(&block) : args)
end
private :permitted_params
end
end
# Configure the index page for the resource
def index(options = {}, &block)
options[:as] ||= :table
config.set_page_presenter :index, ActiveAdmin::PagePresenter.new(options, &block)
end
# Configure the show page for the resource
def show(options = {}, &block)
config.set_page_presenter :show, ActiveAdmin::PagePresenter.new(options, &block)
end
def form(options = {}, &block)
config.set_page_presenter :form, ActiveAdmin::PagePresenter.new(options, &block)
end
# Configure the CSV format
#
# For example:
#
# csv do
# column :name
# column("Author") { |post| post.author.full_name }
# end
#
# csv col_sep: ";", force_quotes: true do
# column :name
# end
#
def csv(options = {}, &block)
options[:resource] = config
config.csv_builder = CSVBuilder.new(options, &block)
end
# Member Actions give you the functionality of defining both the
# action and the route directly from your ActiveAdmin registration
# block.
#
# For example:
#
# ActiveAdmin.register Post do
# member_action :comments do
# @post = Post.find(params[:id])
# @comments = @post.comments
# end
# end
#
# Will create a new controller action comments and will hook it up to
# the named route (comments_admin_post_path) /admin/posts/:id/comments
#
# You can treat everything within the block as a standard Rails controller
# action.
#
def action(set, name, options = {}, &block)
warn "Warning: method `#{name}` already defined in #{controller.name}" if controller.method_defined?(name)
set << ControllerAction.new(name, options)
title = options.delete(:title)
controller do
before_action(only: [name]) { @page_title = title } if title
define_method(name, &block || Proc.new {})
end
end
def member_action(name, options = {}, &block)
action config.member_actions, name, options, &block
end
def collection_action(name, options = {}, &block)
action config.collection_actions, name, options, &block
end
def decorate_with(decorator_class)
# Force storage as a string. This will help us with reloading issues.
# Assuming decorator_class.to_s will return the name of the class allows
# us to handle a string or a class.
config.decorator_class_name = "::#{ decorator_class }"
end
# Defined Callbacks
#
# == After Build
# Called after the resource is built in the new and create actions.
#
# ActiveAdmin.register Post do
# after_build do |post|
# post.author = current_user
# end
# end
#
# == Before / After Create
# Called before and after a resource is saved to the db on the create action.
#
# == Before / After Update
# Called before and after a resource is saved to the db on the update action.
#
# == Before / After Save
# Called before and after the object is saved in the create and update action.
# Note: Gets called after the create and update callbacks
#
# == Before / After Destroy
# Called before and after the object is destroyed from the database.
#
delegate :before_build, :after_build, to: :controller
delegate :before_create, :after_create, to: :controller
delegate :before_update, :after_update, to: :controller
delegate :before_save, :after_save, to: :controller
delegate :before_destroy, :after_destroy, to: :controller
standard_rails_filters =
AbstractController::Callbacks::ClassMethods.public_instance_methods.select { |m| m.end_with?('_action') }
delegate(*standard_rails_filters, to: :controller)
# Specify which actions to create in the controller
#
# Eg:
#
# ActiveAdmin.register Post do
# actions :index, :show
# end
#
# Will only create the index and show actions (no create, update or delete)
delegate :actions, to: :controller
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/dependency.rb | lib/active_admin/dependency.rb | # frozen_string_literal: true
module ActiveAdmin
module Dependency
module Requirements
DEVISE = ">= 4.0", "< 5"
end
# Provides a clean interface to check for gem dependencies at runtime.
#
# ActiveAdmin::Dependency.rails
# => #<ActiveAdmin::Dependency::Matcher for rails 6.0.3.2>
#
# ActiveAdmin::Dependency.rails?
# => true
#
# ActiveAdmin::Dependency.rails? '>= 6.1'
# => false
#
# ActiveAdmin::Dependency.rails? '= 6.0.3.2'
# => true
#
# ActiveAdmin::Dependency.rails? '~> 6.0.3'
# => true
#
# ActiveAdmin::Dependency.rails? '>= 6.0.3', '<= 6.1.0'
# => true
#
# ActiveAdmin::Dependency.rails! '5'
# -> ActiveAdmin::DependencyError: You provided rails 4.2.7 but we need: 5.
#
# ActiveAdmin::Dependency.devise!
# -> ActiveAdmin::DependencyError: To use devise you need to specify it in your Gemfile.
#
#
# All but the pessimistic operator (~>) can also be run using Ruby's comparison syntax.
#
# ActiveAdmin::Dependency.rails >= '4.2.7'
# => true
#
# Which is especially useful if you're looking up a gem with dashes in the name.
#
# ActiveAdmin::Dependency['jquery-rails'] < 5
# => false
#
def self.method_missing(name, *args)
if name[-1] == "?"
Matcher.new(name[0..-2]).match? args
elsif name[-1] == "!"
Matcher.new(name[0..-2]).match! args
else
Matcher.new name.to_s
end
end
def self.[](name)
Matcher.new name.to_s
end
class Matcher
attr_reader :name
def initialize(name)
@name = name
end
def spec
@spec ||= Gem.loaded_specs[name]
end
def spec!
spec || raise(DependencyError, "To use #{name} you need to specify it in your Gemfile.")
end
def match?(*reqs)
!!spec && Gem::Requirement.create(reqs).satisfied_by?(spec.version)
end
def match!(*reqs)
unless match? reqs
raise DependencyError, "You provided #{spec!.name} #{spec!.version} but we need: #{reqs.join ', '}."
end
end
include Comparable
def <=>(other)
spec!.version <=> Gem::Version.create(other)
end
def inspect
info = spec ? "#{spec.name} #{spec.version}" : "(missing)"
"<ActiveAdmin::Dependency::Matcher for #{info}>"
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/sidebar_section.rb | lib/active_admin/sidebar_section.rb | # frozen_string_literal: true
module ActiveAdmin
class SidebarSection
include ActiveAdmin::OptionalDisplay
attr_accessor :name, :options, :block
def initialize(name, options = {}, &block)
@name = name.to_s
@options = options
@block = block
normalize_display_options!
end
# The id gets used for the div in the view
def id
"#{name.downcase.underscore}_sidebar_section".parameterize
end
# If a block is not passed in, the name of the partial to render
def partial_name
options[:partial] || "#{name.downcase.tr(' ', '_')}_sidebar"
end
def custom_class
options[:class]
end
def priority
options[:priority] || 10
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/inputs.rb | lib/active_admin/inputs.rb | # frozen_string_literal: true
module ActiveAdmin
module Inputs
extend ActiveSupport::Autoload
module Filters
extend ActiveSupport::Autoload
autoload :Base
autoload :StringInput
autoload :TextInput
autoload :DateRangeInput
autoload :NumericInput
autoload :SelectInput
autoload :CheckBoxesInput
autoload :BooleanInput
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/error.rb | lib/active_admin/error.rb | # frozen_string_literal: true
module ActiveAdmin
# Exception class to raise when there is an authorized access
# exception thrown. The exception has a few goodies that may
# be useful for capturing / recognizing security issues.
class AccessDenied < StandardError
attr_reader :user, :action, :subject
def initialize(user, action, subject = nil)
@user = user
@action = action
@subject = subject
super()
end
def message
I18n.t("active_admin.access_denied.message")
end
end
class Error < RuntimeError
end
class ErrorLoading < Error
# Locates the most recent file and line from the caught exception's backtrace.
def find_cause(folder, backtrace)
backtrace.grep(/\/(#{folder}\/.*\.rb):(\d+)/) { [$1, $2] }.first
end
end
class DatabaseHitDuringLoad < ErrorLoading
def initialize(exception)
file, line = find_cause(:app, exception.backtrace)
super "Your file, #{file} (line #{line}), caused a database error while Active Admin was loading. This " +
"is most common when your database is missing or doesn't have the latest migrations applied. To " +
"prevent this error, move the code to a place where it will only be run when a page is rendered. " +
"One solution can be, to wrap the query in a Proc. " +
"Original error message: #{exception.message}"
end
def self.capture
yield
rescue *database_error_classes => exception
raise new exception
end
def self.database_error_classes
@classes ||= []
end
end
class DependencyError < ErrorLoading
end
class NoMenuError < KeyError
end
class GeneratorError < Error
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/csv_builder.rb | lib/active_admin/csv_builder.rb | # frozen_string_literal: true
module ActiveAdmin
# CSVBuilder stores CSV configuration
#
# Usage example:
#
# csv_builder = CSVBuilder.new
# csv_builder.column :id
# csv_builder.column("Name") { |resource| resource.full_name }
# csv_builder.column(:name, humanize_name: false)
# csv_builder.column("name", humanize_name: false) { |resource| resource.full_name }
#
# csv_builder = CSVBuilder.new col_sep: ";"
# csv_builder = CSVBuilder.new humanize_name: false
# csv_builder.column :id
#
#
class CSVBuilder
# Return a default CSVBuilder for a resource
# The CSVBuilder's columns would be Id followed by this
# resource's content columns
def self.default_for_resource(resource)
new resource: resource do
column :id
resource.content_columns.each { |c| column c }
end
end
attr_reader :columns, :options, :view_context
COLUMN_TRANSITIVE_OPTIONS = [:humanize_name].freeze
def initialize(options = {}, &block)
@resource = options.delete(:resource)
@columns = []
@options = ActiveAdmin.application.csv_options.merge options
@block = block
end
def column(name, options = {}, &block)
@columns << Column.new(name, @resource, column_transitive_options.merge(options), block)
end
def build(controller, csv)
columns = exec_columns controller.view_context
bom = options[:byte_order_mark]
column_names = options.delete(:column_names) { true }
csv_options = options.except :encoding_options, :humanize_name, :byte_order_mark
csv << bom if bom
if column_names
csv << CSV.generate_line(columns.map { |c| sanitize(encode(c.name, options)) }, **csv_options)
end
controller.send(:in_paginated_batches) do |resource|
csv << CSV.generate_line(build_row(resource, columns, options), **csv_options)
end
csv
end
def exec_columns(view_context = nil)
@view_context = view_context
@columns = [] # we want to re-render these every instance
instance_exec(&@block) if @block.present?
columns
end
def build_row(resource, columns, options)
columns.map do |column|
sanitize(encode(call_method_or_proc_on(resource, column.data), options))
end
end
def encode(content, options)
if options[:encoding]
if options[:encoding_options]
content.to_s.encode options[:encoding], **options[:encoding_options]
else
content.to_s.encode options[:encoding]
end
else
content
end
end
def sanitize(content)
Sanitizer.sanitize(content)
end
def method_missing(method, *args, &block)
if @view_context.respond_to? method
@view_context.public_send method, *args, &block
else
super
end
end
class Column
attr_reader :name, :data, :options
DEFAULT_OPTIONS = { humanize_name: true }
def initialize(name, resource = nil, options = {}, block = nil)
@options = options.reverse_merge(DEFAULT_OPTIONS)
@name = humanize_name(name, resource, @options[:humanize_name])
@data = block || name.to_sym
end
def humanize_name(name, resource, humanize_name_option)
if humanize_name_option
name.is_a?(Symbol) && resource ? resource.resource_class.human_attribute_name(name) : name.to_s.humanize
else
name.to_s
end
end
end
private
def column_transitive_options
@column_transitive_options ||= @options.slice(*COLUMN_TRANSITIVE_OPTIONS)
end
end
# Prevents CSV Injection according to https://owasp.org/www-community/attacks/CSV_Injection
module Sanitizer
extend self
ATTACK_CHARACTERS = ['=', '+', '-', '@', "\t", "\r"].freeze
def sanitize(value)
return "'#{value}" if require_sanitization?(value)
value
end
def require_sanitization?(value)
value.is_a?(String) && value.starts_with?(*ATTACK_CHARACTERS)
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/page_dsl.rb | lib/active_admin/page_dsl.rb | # frozen_string_literal: true
module ActiveAdmin
# This is the class where all the register_page blocks are evaluated.
class PageDSL < DSL
# Page content.
#
# The block should define the view using Arbre.
#
# Example:
#
# ActiveAdmin.register "My Page" do
# content do
# para "Sweet!"
# end
# end
#
def content(options = {}, &block)
config.set_page_presenter :index, ActiveAdmin::PagePresenter.new(options, &block)
end
def page_action(name, options = {}, &block)
config.page_actions << ControllerAction.new(name, options)
controller do
define_method(name, &block || Proc.new {})
end
end
def belongs_to(target, options = {})
config.belongs_to(target, options)
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/batch_actions/controller.rb | lib/active_admin/batch_actions/controller.rb | # frozen_string_literal: true
module ActiveAdmin
module BatchActions
module Controller
# Controller action that is called when submitting the batch action form
def batch_action
if action_present?
selection = params[:collection_selection] || []
inputs = JSON.parse(params[:batch_action_inputs].presence || "{}")
instance_exec selection, inputs, ¤t_batch_action.block
else
raise "Couldn't find batch action \"#{params[:batch_action]}\""
end
end
protected
def action_present?
params[:batch_action].present? && current_batch_action
end
def current_batch_action
active_admin_config.batch_actions.detect { |action| action.sym.to_s == params[:batch_action] }
end
COLLECTION_APPLIES = [
:authorization_scope,
:filtering,
:scoping,
:includes,
].freeze
def batch_action_collection(only = COLLECTION_APPLIES)
find_collection(only: only)
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/batch_actions/resource_extension.rb | lib/active_admin/batch_actions/resource_extension.rb | # frozen_string_literal: true
module ActiveAdmin
module BatchActions
module ResourceExtension
def initialize(*)
super
@batch_actions = {}
add_default_batch_action
end
# @return [Array] The set of batch actions for this resource
def batch_actions
batch_actions_enabled? ? @batch_actions.values.sort : []
end
# @return [Boolean] If batch actions are enabled for this resource
def batch_actions_enabled?
# If the resource config has been set, use it. Otherwise
# return the namespace setting
@batch_actions_enabled.nil? ? namespace.batch_actions : @batch_actions_enabled
end
# Disable or Enable batch actions for this resource
# Set to `nil` to inherit the setting from the namespace
def batch_actions=(bool)
@batch_actions_enabled = bool
end
# Add a new batch item to a resource
# @param [String] title
# @param [Hash] options
# => :if is a proc that will be called to determine if the BatchAction should be displayed
# => :sort_order is used to sort the batch actions ascending
# => :confirm is a string to prompt the user with (or a boolean to use the default message)
# => :form is a Hash of form fields you want the user to fill out
#
def add_batch_action(sym, title, options = {}, &block)
@batch_actions[sym] = ActiveAdmin::BatchAction.new(sym, title, options, &block)
end
# Remove a batch action
# @param [Symbol] sym
# @return [ActiveAdmin::BatchAction] the batch action, if it was present
#
def remove_batch_action(sym)
@batch_actions.delete(sym.to_sym)
end
# Clears all the existing batch actions for this resource
def clear_batch_actions!
@batch_actions = {}
end
private
# @return [ActiveAdmin::BatchAction] The default "delete" action
def add_default_batch_action
destroy_options = {
priority: 100,
confirm: proc { I18n.t("active_admin.batch_actions.delete_confirmation", plural_model: active_admin_config.plural_resource_label.downcase) },
if: proc { destroy_action_authorized?(active_admin_config.resource_class) }
}
add_batch_action :destroy, proc { I18n.t("active_admin.delete") }, destroy_options do |selected_ids|
batch_action_collection.find(selected_ids).each do |record|
authorize! ActiveAdmin::Auth::DESTROY, record
destroy_resource(record)
end
redirect_to active_admin_config.route_collection_path(params),
notice: I18n.t(
"active_admin.batch_actions.successfully_destroyed",
count: selected_ids.count,
model: active_admin_config.resource_label.downcase,
plural_model: active_admin_config.plural_resource_label(count: selected_ids.count).downcase)
end
end
end
end
class BatchAction
include Comparable
attr_reader :block, :title, :sym, :partial, :link_html_options
DEFAULT_CONFIRM_MESSAGE = proc { I18n.t "active_admin.batch_actions.default_confirmation" }
# Create a Batch Action
#
# Examples:
#
# BatchAction.new :flag
# => Will create an action that appears in the action list popover
#
# BatchAction.new(:flag) { |selection| redirect_to collection_path, notice: "#{selection.length} users flagged" }
# => Will create an action that uses a block to process the request (which receives one parameter of the selected objects)
#
# BatchAction.new("Perform Long Operation on") { |selection| }
# => You can create batch actions with a title instead of a Symbol
#
# BatchAction.new(:flag, if: proc{ can? :flag, AdminUser }) { |selection| }
# => You can provide an `:if` proc to choose when the batch action should be displayed
#
# BatchAction.new :flag, confirm: true
# => You can pass `true` to `:confirm` to use the default confirm message.
#
# BatchAction.new(:flag, confirm: "Are you sure?") { |selection| }
# => You can pass a custom confirmation message through `:confirm`
#
# BatchAction.new(:flag, partial: "flag_form", link_html_options: { "data-modal-target": "modal-id", "data-modal-show": "modal-id" }) { |selection, inputs| }
# => Pass a partial that contains a modal and with a data attribute that opens the modal with the form for the user to fill out.
#
def initialize(sym, title, options = {}, &block)
@sym = sym
@title = title
@options = options
@block = block
@confirm = options[:confirm]
@partial = options[:partial]
@link_html_options = options[:link_html_options] || {}
@block ||= proc {}
end
def confirm
if @confirm == true
DEFAULT_CONFIRM_MESSAGE
else
@confirm
end
end
# Returns the display if block. If the block was not explicitly defined
# a default block always returning true will be returned.
def display_if_block
@options[:if] || proc { true }
end
# Used for sorting
def priority
@options[:priority] || 10
end
# sort operator
def <=>(other)
self.priority <=> other.priority
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/batch_actions/views/selection_cells.rb | lib/active_admin/batch_actions/views/selection_cells.rb | # frozen_string_literal: true
require_relative "../../component"
module ActiveAdmin
module BatchActions
# Creates the toggle checkbox used to toggle the collection selection on/off
class ResourceSelectionToggleCell < ActiveAdmin::Component
builder_method :resource_selection_toggle_cell
def build(label_text = "")
label do
input type: "checkbox", id: "collection_selection_toggle_all", name: "collection_selection_toggle_all", class: "batch-actions-toggle-all"
text_node label_text if label_text.present?
end
end
end
# Creates the checkbox used to select a resource in the collection selection
class ResourceSelectionCell < ActiveAdmin::Component
builder_method :resource_selection_cell
def build(resource)
input type: "checkbox", id: "batch_action_item_#{resource.id}", value: resource.id, class: "batch-actions-resource-selection", name: "collection_selection[]"
end
end
# Creates a wrapper panel for all index pages, except for the table, as the table has the checkbox in the thead
class ResourceSelectionTogglePanel < ActiveAdmin::Component
builder_method :resource_selection_toggle_panel
def build
super(id: "collection_selection_toggle_panel")
resource_selection_toggle_cell(I18n.t("active_admin.batch_actions.selection_toggle_explanation", default: "(Toggle Selection)"))
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/batch_actions/views/batch_action_form.rb | lib/active_admin/batch_actions/views/batch_action_form.rb | # frozen_string_literal: true
require_relative "../../component"
module ActiveAdmin
module BatchActions
# Build a BatchActionForm
class BatchActionForm < ActiveAdmin::Component
def build(options = {}, &block)
options[:id] ||= "collection_selection"
# Open a form with two hidden input fields:
# batch_action => name of the specific action called
# batch_action_inputs => a JSON string of any requested confirmation values
text_node form_tag active_admin_config.route_batch_action_path(params, url_options), id: options[:id]
input name: :batch_action, id: :batch_action, type: :hidden
input name: :batch_action_inputs, id: :batch_action_inputs, type: :hidden
super(options)
end
# Override the default to_s to include a closing form tag
def to_s
content + closing_form_tag
end
private
def closing_form_tag
"</form>".html_safe
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/resource/attributes.rb | lib/active_admin/resource/attributes.rb | # frozen_string_literal: true
module ActiveAdmin
class Resource
module Attributes
def default_attributes
resource_class.columns.each_with_object({}) do |c, attrs|
unless reject_col?(c)
name = c.name.to_sym
attrs[name] = (method_for_column(name) || name)
end
end
end
def method_for_column(c)
resource_class.respond_to?(:reflect_on_all_associations) && foreign_methods.has_key?(c) && foreign_methods[c].name.to_sym
end
def foreign_methods
@foreign_methods ||= resource_class.reflect_on_all_associations.
select { |r| r.macro == :belongs_to }.
reject { |r| r.chain.length > 2 && !r.options[:polymorphic] }.
index_by { |r| r.foreign_key.to_sym }
end
def reject_col?(c)
primary_col?(c) || sti_col?(c) || counter_cache_col?(c) || filtered_col?(c)
end
def primary_col?(c)
c.name == resource_class.primary_key
end
def sti_col?(c)
c.name == resource_class.inheritance_column
end
def counter_cache_col?(c)
# This helper is called inside a loop. Let's memoize the result.
@counter_cache_columns ||= begin
resource_class.reflect_on_all_associations(:has_many)
.select(&:has_cached_counter?)
.map(&:counter_cache_column)
end
@counter_cache_columns.include?(c.name)
end
def filtered_col?(c)
ActiveAdmin.application.filter_attributes.include?(c.name.to_sym)
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/resource/menu.rb | lib/active_admin/resource/menu.rb | # frozen_string_literal: true
module ActiveAdmin
class Resource
module Menu
# Set the menu options.
# To disable this menu item, call `menu(false)` from the DSL
def menu_item_options=(options)
if options == false
@include_in_menu = false
@menu_item_options = {}
else
@include_in_menu = true
@navigation_menu_name = options[:menu_name]
@menu_item_options = default_menu_options.merge options
end
end
def menu_item_options
@menu_item_options ||= default_menu_options
end
def default_menu_options
# These local variables are accessible to the procs.
menu_resource_class = respond_to?(:resource_class) ? resource_class : self
resource = self
{
id: resource_name.plural,
label: proc { resource.plural_resource_label },
url: proc { resource.route_collection_path(params, url_options) },
if: proc { authorized?(Auth::READ, menu_resource_class) }
}
end
def navigation_menu_name=(menu_name)
self.menu_item_options = { menu_name: menu_name }
end
def navigation_menu_name
case @navigation_menu_name ||= DEFAULT_MENU
when Proc
controller.instance_exec(&@navigation_menu_name).to_sym
else
@navigation_menu_name
end
end
def navigation_menu
namespace.fetch_menu(navigation_menu_name)
end
def add_to_menu(menu_collection)
if include_in_menu?
@menu_item = menu_collection.add navigation_menu_name, menu_item_options
end
end
attr_reader :menu_item
# Should this resource be added to the menu system?
def include_in_menu?
@include_in_menu != false
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/resource/scope_to.rb | lib/active_admin/resource/scope_to.rb | # frozen_string_literal: true
module ActiveAdmin
class Resource
module ScopeTo
# Scope this controller to some object which has a relation
# to the resource. Can either accept a block or a symbol
# of a method to call.
#
# Eg:
#
# ActiveAdmin.register Post do
# scope_to :current_user
# end
#
# Then every time we instantiate and object, it would call
#
# current_user.posts.build
#
# By default Active Admin will use the resource name to build a
# method to call as the association. If its different, you can
# pass in the association_method as an option.
#
# scope_to :current_user, association_method: :blog_posts
#
# will result in the following
#
# current_user.blog_posts.build
#
# To conditionally use this scope, you can use conditional procs
#
# scope_to :current_user, if: proc{ admin_user_signed_in? }
#
# or
#
# scope_to :current_user, unless: proc{ current_user.admin? }
#
def scope_to(*args, &block)
options = args.extract_options!
method = args.first
scope_to_config[:method] = block || method
scope_to_config[:association_method] = options[:association_method]
scope_to_config[:if] = options[:if]
scope_to_config[:unless] = options[:unless]
end
def scope_to_association_method
scope_to_config[:association_method]
end
def scope_to_method
scope_to_config[:method]
end
def scope_to_config
@scope_to_config ||= {
method: nil,
association_method: nil,
if: nil,
unless: nil
}
end
def scope_to?(context = nil)
return false if scope_to_method.nil?
return render_in_context(context, scope_to_config[:if]) unless scope_to_config[:if].nil?
return !render_in_context(context, scope_to_config[:unless]) unless scope_to_config[:unless].nil?
true
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/resource/controllers.rb | lib/active_admin/resource/controllers.rb | # frozen_string_literal: true
module ActiveAdmin
class Resource
module Controllers
delegate :resources_configuration, to: :controller
# Returns a properly formatted controller name for this
# config within its namespace
def controller_name
[namespace.module_name, resource_name.plural.camelize + "Controller"].compact.join("::")
end
# Returns the controller for this config
def controller
@controller ||= controller_name.constantize
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/resource/sidebars.rb | lib/active_admin/resource/sidebars.rb | # frozen_string_literal: true
require_relative "../helpers/optional_display"
module ActiveAdmin
class Resource
module Sidebars
def sidebar_sections
@sidebar_sections ||= []
end
def clear_sidebar_sections!
@sidebar_sections = []
end
def sidebar_sections_for(action, render_context = nil)
sidebar_sections.select { |section| section.display_on?(action, render_context) }
.sort_by(&:priority)
end
def sidebar_sections?
!!@sidebar_sections && @sidebar_sections.any?
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/resource/routes.rb | lib/active_admin/resource/routes.rb | # frozen_string_literal: true
module ActiveAdmin
class Resource
module Routes
# @param params [Hash] of params: { study_id: 3 }
# @return [String] the path to this resource collection page
# @example "/admin/posts"
def route_collection_path(params = {}, additional_params = {})
route_builder.collection_path(params, additional_params)
end
def route_batch_action_path(params = {}, additional_params = {})
route_builder.batch_action_path(params, additional_params)
end
# @param resource [ActiveRecord::Base] the instance we want the path of
# @return [String] the path to this resource collection page
# @example "/admin/posts/1"
def route_instance_path(resource, additional_params = {})
route_builder.instance_path(resource, additional_params)
end
def route_edit_instance_path(resource, additional_params = {})
route_builder.member_action_path(:edit, resource, additional_params)
end
def route_member_action_path(action, resource, additional_params = {})
route_builder.member_action_path(action, resource, additional_params)
end
# Returns the routes prefix for this config
def route_prefix
namespace.route_prefix
end
def route_builder
@route_builder ||= RouteBuilder.new(self)
end
def route_uncountable?
config = resources_configuration[:self]
config[:route_collection_name] == config[:route_instance_name]
end
class RouteBuilder
def initialize(resource)
@resource = resource
end
def collection_path(params, additional_params = {})
route_name = route_name(
resource.resources_configuration[:self][:route_collection_name],
suffix: (resource.route_uncountable? ? "index_path" : "path")
)
routes.public_send route_name, *route_collection_params(params), additional_params
end
def batch_action_path(params, additional_params = {})
route_name = route_name(
resource.resources_configuration[:self][:route_collection_name],
action: :batch_action,
suffix: (resource.route_uncountable? ? "index_path" : "path")
)
query = params.slice(:q, :scope)
query = query.permit!.to_h
routes.public_send route_name, *route_collection_params(params), additional_params.merge(query)
end
# @return [String] the path to this resource collection page
# @param instance [ActiveRecord::Base] the instance we want the path of
# @example "/admin/posts/1"
def instance_path(instance, additional_params = {})
route_name = route_name(resource.resources_configuration[:self][:route_instance_name])
routes.public_send route_name, *route_instance_params(instance), additional_params
end
# @return [String] the path to the member action of this resource
# @param action [Symbol]
# @param instance [ActiveRecord::Base] the instance we want the path of
# @example "/admin/posts/1/edit"
def member_action_path(action, instance, additional_params = {})
path = resource.resources_configuration[:self][:route_instance_name]
route_name = route_name(path, action: action)
routes.public_send route_name, *route_instance_params(instance), additional_params
end
private
attr_reader :resource
def route_name(resource_path_name, options = {})
suffix = options[:suffix] || "path"
route = []
route << options[:action] # "batch_action", "edit" or "new"
route << resource.route_prefix # "admin"
route << belongs_to_name if nested? # "category"
route << resource_path_name # "posts" or "post"
route << suffix # "path" or "index path"
route.compact.join("_").to_sym # :admin_category_posts_path
end
# @return params to pass to instance path
def route_instance_params(instance)
if nested?
[instance.public_send(belongs_to_target_name).to_param, instance.to_param]
else
instance.to_param
end
end
def route_collection_params(params)
if nested?
params[:"#{belongs_to_name}_id"]
end
end
def nested?
resource.belongs_to? && belongs_to_config.required?
end
def belongs_to_target_name
belongs_to_config.target_name
end
def belongs_to_name
belongs_to_config.target.resource_name.singular
end
def belongs_to_config
resource.belongs_to_config
end
def routes
Helpers::Routes
end
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/resource/pagination.rb | lib/active_admin/resource/pagination.rb | # frozen_string_literal: true
module ActiveAdmin
class Resource
module Pagination
# The default number of records to display per page
attr_accessor :per_page
# The default number of records to display per page
attr_accessor :max_per_page
# Enable / disable pagination (defaults to true)
attr_accessor :paginate
def initialize(*args)
super
@paginate = true
@per_page = namespace.default_per_page
@max_per_page = namespace.max_per_page
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/resource/action_items.rb | lib/active_admin/resource/action_items.rb | # frozen_string_literal: true
require_relative "../helpers/optional_display"
module ActiveAdmin
class Resource
module ActionItems
# Adds the default action items to a resource when it's initialized
def initialize(*args)
super
add_default_action_items
end
# @return [Array] The set of action items for this resource
def action_items
@action_items ||= []
end
# Add a new action item to a resource
#
# @param [Symbol] name
# @param [Hash] options valid keys include:
# :only: A single or array of controller actions to display
# this action item on.
# :except: A single or array of controller actions not to
# display this action item on.
# :priority: A single integer value. To control the display order. Default is 10.
def add_action_item(name, options = {}, &block)
self.action_items << ActiveAdmin::ActionItem.new(name, options, &block)
end
def remove_action_item(name)
self.action_items.delete_if { |item| item.name == name }
end
# Returns a set of action items to display for a specific controller action
#
# @param [String, Symbol] action the action to retrieve action items for
#
# @return [Array] Array of ActionItems for the controller actions
def action_items_for(action, render_context = nil)
action_items.select { |item| item.display_on? action, render_context }.sort_by(&:priority)
end
# Clears all the existing action items for this resource
def clear_action_items!
@action_items = []
end
# Used by active_admin Base view
def action_items?
!!@action_items && @action_items.any?
end
private
# Adds the default action items to each resource
def add_default_action_items
add_default_new_action_item
add_default_edit_action_item
add_default_destroy_action_item
end
# Adds the default New link on index
def add_default_new_action_item
add_action_item :new, only: :index, if: -> { new_action_authorized?(active_admin_config.resource_class) } do
localizer = ActiveAdmin::Localizers.resource(active_admin_config)
link_to localizer.t(:new_model), new_resource_path, class: "action-item-button"
end
end
# Adds the default Edit link on show
def add_default_edit_action_item
add_action_item :edit, only: :show, if: -> { edit_action_authorized?(resource) } do
localizer = ActiveAdmin::Localizers.resource(active_admin_config)
link_to localizer.t(:edit_model), edit_resource_path(resource), class: "action-item-button"
end
end
# Adds the default Destroy link on show
def add_default_destroy_action_item
add_action_item :destroy, only: :show, if: -> { destroy_action_authorized?(resource) } do
localizer = ActiveAdmin::Localizers.resource(active_admin_config)
link_to(
localizer.t(:delete_model),
resource_path(resource),
class: "action-item-button",
method: :delete,
data: { confirm: localizer.t(:delete_confirmation) }
)
end
end
end
end
# Model class to store the data for ActionItems
class ActionItem
include ActiveAdmin::OptionalDisplay
attr_accessor :block, :name
def initialize(name, options = {}, &block)
@name = name
@options = options
@block = block
normalize_display_options!
end
def priority
@options[:priority] || 10
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/resource/scopes.rb | lib/active_admin/resource/scopes.rb | # frozen_string_literal: true
module ActiveAdmin
class Resource
module Scopes
# Return an array of scopes for this resource
def scopes
@scopes ||= []
end
# Returns a scope for this object by its identifier
def get_scope_by_id(id)
id = id.to_s
scopes.find { |s| s.id == id }
end
def default_scope(context = nil)
scopes.detect do |scope|
if scope.default_block.is_a?(Proc)
render_in_context(context, scope.default_block)
else
scope.default_block
end
end
end
# Create a new scope object for this resource.
# If you want to internationalize the scope name, you can add
# to your i18n files a key like "active_admin.scopes.scope_method".
def scope(*args, &block)
default_options = { show_count: namespace.scopes_show_count }
options = default_options.merge(args.extract_options!)
title = args[0] rescue nil
method = args[1] rescue nil
options[:localizer] ||= ActiveAdmin::Localizers.resource(self)
scope = ActiveAdmin::Scope.new(title, method, options, &block)
# Finds and replaces a scope by the same name if it already exists
existing_scope_index = scopes.index { |existing_scope| existing_scope.id == scope.id }
if existing_scope_index
scopes.delete_at(existing_scope_index)
scopes.insert(existing_scope_index, scope)
else
self.scopes << scope
end
scope
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/resource/includes.rb | lib/active_admin/resource/includes.rb | # frozen_string_literal: true
module ActiveAdmin
class Resource
module Includes
# Return an array of includes for this resource
def includes
@includes ||= []
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/resource/belongs_to.rb | lib/active_admin/resource/belongs_to.rb | # frozen_string_literal: true
module ActiveAdmin
class Resource
class BelongsTo
class TargetNotFound < StandardError
def initialize(key, namespace)
super "Could not find #{key} in #{namespace.name} " +
"with #{namespace.resources.map(&:resource_name)}"
end
end
# The resource which initiated this relationship
attr_reader :owner
# The name of the relation
attr_reader :target_name
def initialize(owner, target_name, options = {})
@owner = owner
@target_name = target_name
@options = options
end
# Returns the target resource class or raises an exception if it doesn't exist
def target
resource or raise TargetNotFound.new (@options[:class_name] || @target_name.to_s.camelize), namespace
end
def resource
namespace.resources[@options[:class_name]] ||
namespace.resources[@target_name.to_s.camelize]
end
def namespace
@owner.namespace
end
def optional?
@options[:optional]
end
def required?
!optional?
end
def to_param
(@options[:param] || "#{@target_name}_id").to_sym
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
activeadmin/activeadmin | https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/lib/active_admin/resource/page_presenters.rb | lib/active_admin/resource/page_presenters.rb | # frozen_string_literal: true
module ActiveAdmin
class Resource
module PagePresenters
# for setting default css class in admin ui
def default_index_class
@default_index
end
# A hash of page configurations for the controller indexed by action name
def page_presenters
@page_presenters ||= {}
end
# Sets a page config for a given action
#
# @param [String, Symbol] action The action to store this configuration for
# @param [PagePresenter] page_presenter The instance of PagePresenter to store
def set_page_presenter(action, page_presenter)
if action.to_s == "index" && page_presenter[:as]
index_class = find_index_class(page_presenter[:as])
page_presenter_key = index_class.index_name.to_sym
set_index_presenter page_presenter_key, page_presenter
else
page_presenters[action.to_sym] = page_presenter
end
end
# Returns a stored page config
#
# @param [Symbol, String] action The action to get the config for
# @param [String] type The string specified in the presenters index_name method
# @return [PagePresenter, nil]
def get_page_presenter(action, type = nil)
if action.to_s == "index" && type && page_presenters[:index].kind_of?(Hash)
page_presenters[:index][type.to_sym]
elsif action.to_s == "index" && page_presenters[:index].kind_of?(Hash)
page_presenters[:index].default
else
page_presenters[action.to_sym]
end
end
protected
# Stores a config for all index actions supplied
#
# @param [Symbol] index_as The index type to store in the configuration
# @param [PagePresenter] page_presenter The instance of PagePresenter to store
def set_index_presenter(index_as, page_presenter)
page_presenters[:index] ||= {}
#set first index as default value or the index with default param set to to true
if page_presenters[:index].empty? || page_presenter[:default] == true
page_presenters[:index].default = page_presenter
@default_index = find_index_class(page_presenter[:as])
end
page_presenters[:index][index_as] = page_presenter
end
# Returns the actual class for rendering the main content on the index
# page. To set this, use the :as option in the page_presenter block.
#
# @param [Symbol, Class] symbol_or_class The component symbol or class
# @return [Class]
def find_index_class(symbol_or_class)
case symbol_or_class
when Symbol
::ActiveAdmin::Views.const_get("IndexAs" + symbol_or_class.to_s.camelcase)
when Class
symbol_or_class
end
end
end
end
end
| ruby | MIT | b9d630ce22a739d57c9c8b9976807a370e4de140 | 2026-01-04T15:38:25.641812Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.