From d3599d8affa90b60b4e9ab24fdbd35477b5ac06d Mon Sep 17 00:00:00 2001 From: Eugene Kenny Date: Thu, 5 Mar 2020 01:24:14 +0000 Subject: [PATCH] Use index_by and index_with wherever possible Using `index_by` or `index_with` is more concise than `each_with_object` and more performant than `map { ... }.to_h` or `Hash[map { ... }]`. --- .../partial_renderer/collection_caching.rb | 19 ++++++++++--------- .../test/template/form_options_helper_test.rb | 7 ++++--- .../active_record/associations/preloader.rb | 6 ++++-- .../lib/active_record/attribute_methods.rb | 5 +++-- activerecord/lib/active_record/core.rb | 5 ++--- activerecord/lib/active_record/insert_all.rb | 4 +++- .../active_record/relation/calculations.rb | 4 +++- .../lib/active_record/test_fixtures.rb | 5 +++-- .../test/cases/arel/support/fake_record.rb | 6 ++++-- .../test/cases/attribute_methods/read_test.rb | 7 ++++--- activerecord/test/cases/base_test.rb | 7 ++++--- activerecord/test/cases/counter_cache_test.rb | 5 +++-- activesupport/lib/active_support/cache.rb | 5 +++-- .../active_support/cache/mem_cache_store.rb | 3 ++- .../lib/active_support/current_attributes.rb | 3 ++- .../lib/active_support/testing/assertions.rb | 4 +++- railties/lib/rails/generators.rb | 3 ++- 17 files changed, 59 insertions(+), 39 deletions(-) diff --git a/actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb b/actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb index c12a25a5ec..71458185a6 100644 --- a/actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb +++ b/actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require "active_support/core_ext/enumerable" + module ActionView module CollectionCaching # :nodoc: extend ActiveSupport::Concern @@ -88,16 +90,15 @@ module ActionView # If the partial is not already cached it will also be # written back to the underlying cache store. def fetch_or_cache_partial(cached_partials, template, order_by:) - order_by.each_with_object({}) do |cache_key, hash| - hash[cache_key] = - if content = cached_partials[cache_key] - build_rendered_template(content, template) - else - yield.tap do |rendered_partial| - collection_cache.write(cache_key, rendered_partial.body) - end - end + order_by.index_with do |cache_key| + if content = cached_partials[cache_key] + build_rendered_template(content, template) + else + yield.tap do |rendered_partial| + collection_cache.write(cache_key, rendered_partial.body) + end end + end end end end diff --git a/actionview/test/template/form_options_helper_test.rb b/actionview/test/template/form_options_helper_test.rb index dc6990c4b7..403190030d 100644 --- a/actionview/test/template/form_options_helper_test.rb +++ b/actionview/test/template/form_options_helper_test.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require "abstract_unit" +require "active_support/core_ext/enumerable" class Map < Hash def category @@ -67,9 +68,9 @@ class FormOptionsHelperTest < ActionView::TestCase ActiveSupport::TimeZone.prepend FakeZones setup do - ActiveSupport::TimeZone.fake_zones = %w(A B C D E).map do |id| - [ id, FakeZones::FakeZone.new(id) ] - end.to_h + ActiveSupport::TimeZone.fake_zones = %w(A B C D E).index_with do |id| + FakeZones::FakeZone.new(id) + end @fake_timezones = ActiveSupport::TimeZone.all end diff --git a/activerecord/lib/active_record/associations/preloader.rb b/activerecord/lib/active_record/associations/preloader.rb index 411b01bbe4..304d7d1a3a 100644 --- a/activerecord/lib/active_record/associations/preloader.rb +++ b/activerecord/lib/active_record/associations/preloader.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require "active_support/core_ext/enumerable" + module ActiveRecord module Associations # Implements the details of eager loading of Active Record associations. @@ -171,8 +173,8 @@ module ActiveRecord end def records_by_owner - @records_by_owner ||= owners.each_with_object({}) do |owner, result| - result[owner] = Array(owner.association(reflection.name).target) + @records_by_owner ||= owners.index_with do |owner| + Array(owner.association(reflection.name).target) end end diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb index 2d52ccd088..4f65385701 100644 --- a/activerecord/lib/active_record/attribute_methods.rb +++ b/activerecord/lib/active_record/attribute_methods.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require "mutex_m" +require "active_support/core_ext/enumerable" module ActiveRecord # = Active Record Attribute Methods @@ -375,8 +376,8 @@ module ActiveRecord end def attributes_with_values(attribute_names) - attribute_names.each_with_object({}) do |name, attrs| - attrs[name] = _read_attribute(name) + attribute_names.index_with do |name| + _read_attribute(name) end end diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb index 4e5af4ac00..f879abdd28 100644 --- a/activerecord/lib/active_record/core.rb +++ b/activerecord/lib/active_record/core.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require "active_support/core_ext/enumerable" require "active_support/core_ext/hash/indifferent_access" require "active_support/core_ext/string/filters" require "active_support/parameter_filter" @@ -208,9 +209,7 @@ module ActiveRecord keys = hash.keys statement = cached_find_by_statement(keys) { |params| - wheres = keys.each_with_object({}) { |param, o| - o[param] = params.bind - } + wheres = keys.index_with { params.bind } where(wheres).limit(1) } begin diff --git a/activerecord/lib/active_record/insert_all.rb b/activerecord/lib/active_record/insert_all.rb index c002c193b5..0a02b2e550 100644 --- a/activerecord/lib/active_record/insert_all.rb +++ b/activerecord/lib/active_record/insert_all.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require "active_support/core_ext/enumerable" + module ActiveRecord class InsertAll # :nodoc: attr_reader :model, :connection, :inserts, :keys @@ -179,7 +181,7 @@ module ActiveRecord unknown_column = (keys - columns.keys).first raise UnknownAttributeError.new(model.new, unknown_column) if unknown_column - keys.map { |key| [ key, connection.lookup_cast_type_from_column(columns[key]) ] }.to_h + keys.index_with { |key| connection.lookup_cast_type_from_column(columns[key]) } end def format_columns(columns) diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index 23a0b563ef..d134fdb0b8 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require "active_support/core_ext/enumerable" + module ActiveRecord module Calculations # Count the records. @@ -354,7 +356,7 @@ module ActiveRecord if association key_ids = calculated_data.collect { |row| row[group_aliases.first] } key_records = association.klass.base_class.where(association.klass.base_class.primary_key => key_ids) - key_records = Hash[key_records.map { |r| [r.id, r] }] + key_records = key_records.index_by(&:id) end Hash[calculated_data.map do |row| diff --git a/activerecord/lib/active_record/test_fixtures.rb b/activerecord/lib/active_record/test_fixtures.rb index cdd31f7f7a..ad05c793a5 100644 --- a/activerecord/lib/active_record/test_fixtures.rb +++ b/activerecord/lib/active_record/test_fixtures.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require "active_support/core_ext/enumerable" + module ActiveRecord module TestFixtures extend ActiveSupport::Concern @@ -206,8 +208,7 @@ module ActiveRecord end def load_fixtures(config) - fixtures = ActiveRecord::FixtureSet.create_fixtures(fixture_path, fixture_table_names, fixture_class_names, config) - Hash[fixtures.map { |f| [f.name, f] }] + ActiveRecord::FixtureSet.create_fixtures(fixture_path, fixture_table_names, fixture_class_names, config).index_by(&:name) end def instantiate_fixtures diff --git a/activerecord/test/cases/arel/support/fake_record.rb b/activerecord/test/cases/arel/support/fake_record.rb index 5ebeabd4a3..f03c965232 100644 --- a/activerecord/test/cases/arel/support/fake_record.rb +++ b/activerecord/test/cases/arel/support/fake_record.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require "active_support/core_ext/enumerable" + require "date" module FakeRecord class Column < Struct.new(:name, :type) @@ -24,8 +26,8 @@ module FakeRecord ] } @columns_hash = { - "users" => Hash[@columns["users"].map { |x| [x.name, x] }], - "products" => Hash[@columns["products"].map { |x| [x.name, x] }] + "users" => @columns["users"].index_by(&:name), + "products" => @columns["products"].index_by(&:name) } @primary_keys = { "users" => "id", diff --git a/activerecord/test/cases/attribute_methods/read_test.rb b/activerecord/test/cases/attribute_methods/read_test.rb index 54512068ee..198a6a85a2 100644 --- a/activerecord/test/cases/attribute_methods/read_test.rb +++ b/activerecord/test/cases/attribute_methods/read_test.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require "cases/helper" +require "active_support/core_ext/enumerable" module ActiveRecord module AttributeMethods @@ -30,9 +31,9 @@ module ActiveRecord end def self.columns_hash - Hash[attribute_names.map { |name| - [name, FakeColumn.new(name)] - }] + attribute_names.index_with { |name| + FakeColumn.new(name) + } end end end diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index b225be354c..8edca79a3f 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -27,6 +27,7 @@ require "models/bird" require "models/car" require "models/bulb" require "concurrent/atomic/count_down_latch" +require "active_support/core_ext/enumerable" class FirstAbstractClass < ActiveRecord::Base self.abstract_class = true @@ -732,9 +733,9 @@ class BasicsTest < ActiveRecord::TestCase def test_attributes category = Category.new(name: "Ruby") - expected_attributes = category.attribute_names.map do |attribute_name| - [attribute_name, category.public_send(attribute_name)] - end.to_h + expected_attributes = category.attribute_names.index_with do |attribute_name| + category.public_send(attribute_name) + end assert_instance_of Hash, category.attributes assert_equal expected_attributes, category.attributes diff --git a/activerecord/test/cases/counter_cache_test.rb b/activerecord/test/cases/counter_cache_test.rb index cc4f86a0fb..155c637aa3 100644 --- a/activerecord/test/cases/counter_cache_test.rb +++ b/activerecord/test/cases/counter_cache_test.rb @@ -16,6 +16,7 @@ require "models/friendship" require "models/subscriber" require "models/subscription" require "models/book" +require "active_support/core_ext/enumerable" class CounterCacheTest < ActiveRecord::TestCase fixtures :topics, :categories, :categorizations, :cars, :dogs, :dog_lovers, :people, :friendships, :subscribers, :subscriptions, :books @@ -355,8 +356,8 @@ class CounterCacheTest < ActiveRecord::TestCase private def assert_touching(record, *attributes) - record.update_columns attributes.map { |attr| [ attr, 5.minutes.ago ] }.to_h - touch_times = attributes.map { |attr| [ attr, record.public_send(attr) ] }.to_h + record.update_columns attributes.index_with(5.minutes.ago) + touch_times = attributes.index_with { |attr| record.public_send(attr) } yield diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb index 7ec1a66369..bfaca88681 100644 --- a/activesupport/lib/active_support/cache.rb +++ b/activesupport/lib/active_support/cache.rb @@ -3,6 +3,7 @@ require "zlib" require "active_support/core_ext/array/extract_options" require "active_support/core_ext/array/wrap" +require "active_support/core_ext/enumerable" require "active_support/core_ext/module/attribute_accessors" require "active_support/core_ext/numeric/bytes" require "active_support/core_ext/numeric/time" @@ -440,8 +441,8 @@ module ActiveSupport instrument :read_multi, names, options do |payload| reads = read_multi_entries(names, **options) writes = {} - ordered = names.each_with_object({}) do |name, hash| - hash[name] = reads.fetch(name) { writes[name] = yield(name) } + ordered = names.index_with do |name| + reads.fetch(name) { writes[name] = yield(name) } end payload[:hits] = reads.keys diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb index 18a62f52d3..bebe87b019 100644 --- a/activesupport/lib/active_support/cache/mem_cache_store.rb +++ b/activesupport/lib/active_support/cache/mem_cache_store.rb @@ -7,6 +7,7 @@ rescue LoadError => e raise e end +require "active_support/core_ext/enumerable" require "active_support/core_ext/marshal" require "active_support/core_ext/array/extract_options" @@ -162,7 +163,7 @@ module ActiveSupport # Reads multiple entries from the cache implementation. def read_multi_entries(names, **options) - keys_to_names = Hash[names.map { |name| [normalize_key(name, options), name] }] + keys_to_names = names.index_by { |name| normalize_key(name, options) } raw_values = @data.with { |c| c.get_multi(keys_to_names.keys) } values = {} diff --git a/activesupport/lib/active_support/current_attributes.rb b/activesupport/lib/active_support/current_attributes.rb index f6eba2ba44..d2d16b2629 100644 --- a/activesupport/lib/active_support/current_attributes.rb +++ b/activesupport/lib/active_support/current_attributes.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require "active_support/callbacks" +require "active_support/core_ext/enumerable" module ActiveSupport # Abstract super class that provides a thread-isolated attributes singleton, which resets automatically @@ -201,7 +202,7 @@ module ActiveSupport end def compute_attributes(keys) - keys.collect { |key| [ key, public_send(key) ] }.to_h + keys.index_with { |key| public_send(key) } end end end diff --git a/activesupport/lib/active_support/testing/assertions.rb b/activesupport/lib/active_support/testing/assertions.rb index 7ff9fd0532..d564cad808 100644 --- a/activesupport/lib/active_support/testing/assertions.rb +++ b/activesupport/lib/active_support/testing/assertions.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require "active_support/core_ext/enumerable" + module ActiveSupport module Testing module Assertions @@ -89,7 +91,7 @@ module ActiveSupport else difference = args[0] || 1 message = args[1] - Hash[Array(expression).map { |e| [e, difference] }] + Array(expression).index_with(difference) end exps = expressions.keys.map { |e| diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb index df4330486b..fb328c70ef 100644 --- a/railties/lib/rails/generators.rb +++ b/railties/lib/rails/generators.rb @@ -8,6 +8,7 @@ require "rails/command" require "active_support/core_ext/kernel/singleton_class" require "active_support/core_ext/array/extract_options" +require "active_support/core_ext/enumerable" require "active_support/core_ext/hash/deep_merge" require "active_support/core_ext/module/attribute_accessors" require "active_support/core_ext/string/indent" @@ -252,7 +253,7 @@ module Rails lookup(lookups) - namespaces = Hash[subclasses.map { |klass| [klass.namespace, klass] }] + namespaces = subclasses.index_by(&:namespace) lookups.each do |namespace| klass = namespaces[namespace] return klass if klass