Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[7.2-stable] fix attribute sorting across Ruby versions #3162

Merged
merged 2 commits into from
Jan 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions lib/alchemy/resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -188,11 +188,21 @@ def enum_values_collection_for_select(column_name)
end
end

# Returns a sorted array of attributes.
#
# Attribute called "name" comes first.
# Attribute called "updated_at" comes last.
# Boolean type attributes come after non-boolean attributes but before "updated_at".
#
def sorted_attributes
@_sorted_attributes ||= attributes
.sort_by { |attr| (attr[:name] == "name") ? 0 : 1 }
.sort_by! { |attr| (attr[:type] == :boolean) ? 1 : 0 }
.sort_by! { |attr| (attr[:name] == "updated_at") ? 1 : 0 }
@_sorted_attributes ||= attributes.sort_by! do |attr|
[
(attr[:name] == "name") ? 0 : 1,
(attr[:name] == "updated_at") ? 3 : 2,
(attr[:type] == :boolean) ? 2 : 1,
attr[:name]
]
end
end

def editable_attributes
Expand Down
15 changes: 10 additions & 5 deletions spec/libraries/resource_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -314,19 +314,24 @@ module Alchemy
describe "#sorted_attributes" do
subject { resource.sorted_attributes }

let(:random_attrs) do
20.times.map do
double(:column, {name: "some_title", type: :string})
end
end

let(:columns) do
[
double(:column, {name: "title", type: :string}),
random_attrs + [
double(:column, {name: "name", type: :string}),
double(:column, {name: "updated_at", type: :datetime}),
double(:column, {name: "public", type: :boolean})
]
end

it "sorts by name, and updated_at" do
is_expected.to eq([
it "sorts by name, booleans and updated_at" do
expect(subject.uniq!).to eq([
{name: "name", type: :string},
{name: "title", type: :string},
{name: "some_title", type: :string},
{name: "public", type: :boolean},
{name: "updated_at", type: :datetime}
])
Expand Down
Loading