Skip to content

Commit 8714ae3

Browse files
Skip eval and avoid generating all generators inside of the benchmark execution
Looping over the constants instead of using `eval` is a more secure approach. Plus, build the list of generators outside so that we're only benchmarking generator execution. Co-Authored-By: Thiago Araujo <thd.araujo@gmail.com>
1 parent 07769e9 commit 8714ae3

2 files changed

Lines changed: 15 additions & 11 deletions

File tree

.rubocop.yml

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,6 @@ Security/Eval:
5454
Description: The use of eval represents a serious security risk.
5555
Exclude:
5656
- 'lib/faker/default/json.rb'
57-
- 'benchmark/generators.rb'
5857

5958
Style/AsciiComments:
6059
Description: This cop checks for non-ascii (non-English) characters in comments.
@@ -77,7 +76,6 @@ Style/EvalWithLocation:
7776
Description: This cop checks eval method usage. eval can receive source location metadata, that are filename and line number.
7877
Exclude:
7978
- 'lib/faker/default/json.rb'
80-
- 'benchmark/generators.rb'
8179

8280
Style/FormatStringToken:
8381
Description: This cop checks for a consistent style for named format string tokens.

benchmark/generators.rb

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@
33
require 'benchmark/ips'
44
require 'faker'
55

6-
def all_generators
7-
generators.map do |klass|
8-
subclass_methods(klass).flatten
9-
end.flatten.sort
6+
def generators
7+
constants.flat_map do |klass|
8+
subclass_methods(klass)
9+
end
1010
end
1111

12-
def generators
12+
def constants
1313
Faker.constants.delete_if do |subclass|
1414
%i[
1515
Base
@@ -28,13 +28,19 @@ def generators
2828
end
2929

3030
def subclass_methods(subclass)
31-
eval("Faker::#{subclass}.public_methods(false) - Faker::Base.public_methods(false)").sort.map do |method|
32-
"Faker::#{subclass}.#{method}"
33-
end.sort
31+
klass = Faker.const_get(subclass)
32+
33+
public_methods = klass.public_methods(false) - Faker::Base.public_methods(false)
34+
35+
public_methods.sort.map do |method|
36+
[klass, method]
37+
end
3438
end
3539

40+
all_generators = generators
41+
3642
Benchmark.ips do |x|
3743
x.report("Number of generators: #{all_generators.count}") do
38-
all_generators.each { |generator| eval(generator) }
44+
all_generators.each { |klass, generator| klass.send(generator) }
3945
end
4046
end

0 commit comments

Comments
 (0)