Sha256: 1ecddbc9efa5cd4c148452ca150113ec2aa1abb3a9a7e0bd3db37655da461468

Contents?: true

Size: 1.29 KB

Versions: 12

Compression:

Stored size: 1.29 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Performance
      # This cop checks for `OpenStruct.new` calls.
      # Instantiation of an `OpenStruct` invalidates
      # Ruby global method cache as it causes dynamic method
      # definition during program runtime.
      # This could have an effect on performance,
      # especially in case of single-threaded
      # applications with multiple `OpenStruct` instantiations.
      #
      # @example
      #   # bad
      #   class MyClass
      #     def my_method
      #       OpenStruct.new(my_key1: 'my_value1', my_key2: 'my_value2')
      #     end
      #   end
      #
      #   # good
      #   class MyClass
      #     MyStruct = Struct.new(:my_key1, :my_key2)
      #     def my_method
      #       MyStruct.new('my_value1', 'my_value2')
      #     end
      #   end
      #
      class OpenStruct < Base
        MSG = 'Consider using `Struct` over `OpenStruct` ' \
              'to optimize the performance.'
        RESTRICT_ON_SEND = %i[new].freeze

        def_node_matcher :open_struct, <<~PATTERN
          (send (const {nil? cbase} :OpenStruct) :new ...)
        PATTERN

        def on_send(node)
          open_struct(node) do
            add_offense(node.loc.selector)
          end
        end
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
rubocop-performance-1.11.5 lib/rubocop/cop/performance/open_struct.rb
rubocop-performance-1.11.4 lib/rubocop/cop/performance/open_struct.rb
rubocop-performance-1.11.3 lib/rubocop/cop/performance/open_struct.rb
rubocop-performance-1.11.2 lib/rubocop/cop/performance/open_struct.rb
rubocop-performance-1.11.1 lib/rubocop/cop/performance/open_struct.rb
rubocop-performance-1.11.0 lib/rubocop/cop/performance/open_struct.rb
rubocop-performance-1.10.2 lib/rubocop/cop/performance/open_struct.rb
rubocop-performance-1.10.1 lib/rubocop/cop/performance/open_struct.rb
rubocop-performance-1.10.0 lib/rubocop/cop/performance/open_struct.rb
rubocop-performance-1.9.2 lib/rubocop/cop/performance/open_struct.rb
rubocop-performance-1.9.1 lib/rubocop/cop/performance/open_struct.rb
rubocop-performance-1.9.0 lib/rubocop/cop/performance/open_struct.rb