diff --git a/lib/alchemy/resource.rb b/lib/alchemy/resource.rb index 7cb6bc7448..2159bc4a3f 100644 --- a/lib/alchemy/resource.rb +++ b/lib/alchemy/resource.rb @@ -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 diff --git a/spec/libraries/resource_spec.rb b/spec/libraries/resource_spec.rb index 1e283706ce..8960d0ade4 100644 --- a/spec/libraries/resource_spec.rb +++ b/spec/libraries/resource_spec.rb @@ -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} ])