Skip to content

Commit

Permalink
Add Config#for_badge
Browse files Browse the repository at this point in the history
This optimization saves about 5MB of unneeded intermediate hashes...
  • Loading branch information
marcandre committed Jul 20, 2020
1 parent 62bcc12 commit eab62cc
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -5,6 +5,7 @@
### New features

* [#8322](https://github.com/rubocop-hq/rubocop/pull/8322): Support autocorrect for `Style/CaseEquality` cop. ([@fatkodima][])
* [#8339](https://github.com/rubocop-hq/rubocop/pull/8339): Add `Config#for_badge` as an efficient way to get a cop's config merged with its department's. ([@marcandre][])

### Bug fixes

Expand Down
10 changes: 9 additions & 1 deletion lib/rubocop/config.rb
Expand Up @@ -47,7 +47,7 @@ def check
end

def_delegators :@hash, :[], :[]=, :delete, :each, :key?, :keys, :each_key,
:map, :merge, :to_h, :to_hash, :transform_values
:fetch, :map, :merge, :to_h, :to_hash, :transform_values
def_delegators :@validator, :validate, :target_ruby_version

def to_s
Expand Down Expand Up @@ -111,6 +111,14 @@ def for_cop(cop)
@for_cop[cop.respond_to?(:cop_name) ? cop.cop_name : cop]
end

# @return [Config] for the given cop merged with that of its department (if any)
# Note: the 'Enabled' attribute is same as that returned by `for_cop`
def for_badge(badge)
cop_config = for_cop(badge.to_s)
fetch(badge.department.to_s) { return cop_config }
.merge(cop_config)
end

# @return [Config] for the given department name.
# Note: the 'Enabled' attribute will be present only if specified
# at the department's level
Expand Down
3 changes: 1 addition & 2 deletions lib/rubocop/cop/base.rb
Expand Up @@ -189,8 +189,7 @@ def cop_name
def cop_config
# Use department configuration as basis, but let individual cop
# configuration override.
@cop_config ||= @config.for_cop(self.class.department.to_s)
.merge(@config.for_cop(self))
@cop_config ||= @config.for_badge(self.class.badge)
end

def config_to_allow_offenses
Expand Down
25 changes: 25 additions & 0 deletions spec/rubocop/config_spec.rb
Expand Up @@ -735,6 +735,31 @@
end
end

describe '#for_badge' do
let(:hash) do
{
'Style' => { 'Foo' => 42, 'Bar' => 666 },
'Layout/TrailingWhitespace' => { 'Bar' => 43 },
'Style/Alias' => { 'Bar' => 44 }
}
end

it 'takes into account the department' do
expect(configuration.for_badge(RuboCop::Cop::Style::Alias.badge)).to eq(
{ 'Enabled' => true,
'Foo' => 42,
'Bar' => 44 }
)
end

it 'works if department has no config' do
expect(configuration.for_badge(RuboCop::Cop::Layout::TrailingWhitespace.badge)).to eq(
{ 'Enabled' => true,
'Bar' => 43 }
)
end
end

context 'whether the cop is enabled' do
def cop_enabled(cop_class)
configuration.for_cop(cop_class).fetch('Enabled')
Expand Down

0 comments on commit eab62cc

Please sign in to comment.