Skip to content

Commit

Permalink
Merge pull request #3162 from AlchemyCMS/backport/7.2-stable/pr-3153
Browse files Browse the repository at this point in the history
[7.2-stable] fix attribute sorting across Ruby versions
  • Loading branch information
robinboening authored Jan 24, 2025
2 parents af07918 + 064663d commit 9226e2f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 9 deletions.
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

0 comments on commit 9226e2f

Please sign in to comment.