123456789_123456789_123456789_123456789_123456789_

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

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, Base
Instance Chain:
self, Base
Inherits: Base
  • Object
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

Cop Safety Information:

  • This cop is unsafe because OpenStruct.new and Struct.new are not equivalent.

Constant Summary

Instance Method Summary

Instance Method Details

#on_send(node)

[ GitHub ]

  
# 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