-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
open_struct.rb
50 lines (47 loc) · 1.39 KB
/
open_struct.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# frozen_string_literal: true
module RuboCop
module Cop
module Performance
# 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.
#
# @safety
# This cop is unsafe because `OpenStruct.new` and `Struct.new`
# are not equivalent.
#
# @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