Class: RuboCop::Cop::Performance::OpenStruct

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/performance/open_struct.rb

Overview

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.

Examples:

# 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

Constant Summary collapse

MSG =
'Consider using `Struct` over `OpenStruct` to optimize the performance.'
RESTRICT_ON_SEND =
%i[new].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



42
43
44
45
46
# File 'lib/rubocop/cop/performance/open_struct.rb', line 42

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