/
feature_loader.rb
88 lines (76 loc) · 2.12 KB
/
feature_loader.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# frozen_string_literal: true
module RuboCop
# This class handles loading files (a.k.a. features in Ruby) specified
# by `--require` command line option and `require` directive in the config.
#
# Normally, the given string is directly passed to `require`. If a string
# beginning with `.` is given, it is assumed to be relative to the given
# directory.
#
# If a string containing `-` is given, it will be used as is, but if we
# cannot find the file to load, we will replace `-` with `/` and try it
# again as when Bundler loads gems.
#
# @api private
class FeatureLoader
class << self
# @param [String] config_directory_path
# @param [String] feature
def load(config_directory_path:, feature:)
new(config_directory_path: config_directory_path, feature: feature).load
end
end
# @param [String] config_directory_path
# @param [String] feature
def initialize(config_directory_path:, feature:)
@config_directory_path = config_directory_path
@feature = feature
end
def load
::Kernel.require(target)
rescue ::LoadError => e
raise if e.path != target
begin
::Kernel.require(namespaced_target)
rescue ::LoadError => error_for_namespaced_target
raise e if error_for_namespaced_target.path == namespaced_target
raise error_for_namespaced_target
end
end
private
# @return [String]
def namespaced_feature
@feature.tr('-', '/')
end
# @return [String]
def namespaced_target
if relative?
relative(namespaced_feature)
else
namespaced_feature
end
end
# @param [String]
# @return [String]
def relative(feature)
::File.join(@config_directory_path, feature)
end
# @return [Boolean]
def relative?
@feature.start_with?('.')
end
# @param [LoadError] error
# @return [Boolean]
def seems_cannot_load_such_file_error?(error)
error.path == target
end
# @return [String]
def target
if relative?
relative(@feature)
else
@feature
end
end
end
end