Skip to content

Commit

Permalink
Simplify
Browse files Browse the repository at this point in the history
  • Loading branch information
pablobm committed Apr 14, 2022
1 parent d2e4f33 commit d15b3bf
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 16 deletions.
15 changes: 4 additions & 11 deletions app/helpers/administrate/application_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,11 @@ def model_from_resource(resource_name)
# - Class: resource class
# - ActiveRecord::Base: resource instance
def administrate_valid_action?(target, action_name)
begin
target = target.to_s.classify.constantize if target.is_a?(String)
target_class = target.is_a?(ActiveRecord::Base) ? target.class : target
rescue NameError
# If target is a string, Pundit.policy! will try
# to use `StringPolicy`, which doesn't exist.
# If target is a symbol, Pundit.policy! will try
# to use `#{camelized_symbol}Policy`, which is correct.
target = target.to_sym
end
target = target.to_sym if target.is_a?(String)
target_class_or_class_name =
target.is_a?(ActiveRecord::Base) ? target.class : target

valid_action?(action_name, target_class) &&
valid_action?(action_name, target_class_or_class_name) &&
show_action?(action_name, target)
end

Expand Down
2 changes: 1 addition & 1 deletion app/views/administrate/application/_navigation.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ as defined by the routes in the `admin/` namespace
display_resource_name(resource),
resource_index_route(resource),
class: "navigation__link navigation__link--#{nav_link_state(resource)}"
) if administrate_valid_action?(resource, :index) %>
) if administrate_valid_action?(resource.singularize, :index) %>
<% end %>
</nav>
7 changes: 3 additions & 4 deletions spec/helpers/administrate/application_helper_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,10 @@ class MyResource; end
ctx = double(valid_action?: true, show_action?: true)
ctx.extend(Administrate::ApplicationHelper)

result = ctx.administrate_valid_action?("my_resource", "foo")
ctx.administrate_valid_action?("my_resource", "foo")

expect(ctx).to have_received(:valid_action?).with("foo", MyResource)
expect(ctx).to have_received(:show_action?).with("foo", MyResource)
expect(ctx).to have_received(:valid_action?).with("foo", :my_resource)
expect(ctx).to have_received(:show_action?).with("foo", :my_resource)
ensure
remove_constants :MyResource
end
Expand All @@ -126,7 +126,6 @@ class MyResource; end

ctx.administrate_valid_action?(:my_resource, "foo")

# Using a symbol instead of a class is allowed for both methods
expect(ctx).to have_received(:valid_action?).with("foo", :my_resource)
expect(ctx).to have_received(:show_action?).with("foo", :my_resource)
ensure
Expand Down

0 comments on commit d15b3bf

Please sign in to comment.