Skip to content

Commit

Permalink
[Fix rubocop#78] Improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
santib committed Jul 26, 2019
1 parent e437bc6 commit 9c535da
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 36 deletions.
39 changes: 10 additions & 29 deletions lib/rubocop/cop/rails/enum_hash.rb
Expand Up @@ -40,6 +40,16 @@ def on_send(node)
end
end

def autocorrect(node)
range = node.loc.expression
hash = node
.children
.each_with_index
.map { |elem, index| [elem.children.first, index] }.to_h

->(corrector) { corrector.replace(range, hash.to_s) }
end

private

def enum_name(key)
Expand All @@ -50,35 +60,6 @@ def enum_name(key)
key.source
end
end

def autocorrect(node)
enum_values = node.children[2].children.first.children[1]
to_replace = enum_values.loc.expression
values_hash = "{ #{converted_values(enum_values)} }"

->(corrector) { corrector.replace(to_replace, values_hash) }
end

private

def converted_values(enum_values)
enum_values.children.each_with_index.map do |child, index|
hash_entry_as_string(child, index)
end.join(', ')
end

def hash_entry_as_string(child, index)
value = child.children.first
case value
when String
"'#{value}' => #{index}"
when Symbol
value = "'#{value}'" if value =~ /\s/
"#{value}: #{index}"
else
"#{child.source} => #{index}"
end
end
end
end
end
Expand Down
15 changes: 8 additions & 7 deletions spec/rubocop/cop/rails/enum_hash_spec.rb
Expand Up @@ -81,13 +81,14 @@
end

it 'autocorrects' do
expect(
autocorrect_source(
'enum status: [:old, :"very active", "is archived", 42]'
)
).to eq(
"enum status: { old: 0, 'very active': 1, 'is archived' => 2, 42 => 3 }"
)
expect_offense(<<~RUBY)
enum status: [:old, :"very active", "is archived", 42]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Enum defined as an array found in `status` enum declaration. Use hash syntax instead.
RUBY

expect_correction(<<~RUBY)
enum status: {:old=>0, :"very active"=>1, "is archived"=>2, 42=>3}
RUBY
end
end

Expand Down

0 comments on commit 9c535da

Please sign in to comment.