Class: Rubocop::Cop::Style::AlignHash
- Defined in:
- lib/rubocop/cop/style/align_hash.rb
Overview
Here we check if the keys, separators, and values of a multi-line hash literal are aligned.
Constant Summary collapse
- MSG =
'Align the elements of a hash literal if they span more than ' + 'one line.'
Constants inherited from Cop
Instance Attribute Summary
Attributes inherited from Cop
#config, #corrections, #offences, #processed_source
Instance Method Summary collapse
Methods inherited from Cop
#add_offence, all, #autocorrect?, #convention, #cop_config, cop_name, #cop_name, cop_type, #debug?, #ignore_node, inherited, #initialize, lint?, #message, rails?, style?, #warning
Constructor Details
This class inherits a constructor from Rubocop::Cop::Cop
Instance Method Details
#autocorrect_action(node) ⇒ Object
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 |
# File 'lib/rubocop/cop/style/align_hash.rb', line 34 def autocorrect_action(node) # We can't use the instance variable inside the lambda. That would # just give each lambda the same reference and they would all get the # last value of each. Some local variables fix the problem. max_key_width = @max_key_width key_delta = @column_deltas[:key] || 0 key, value = *node @corrections << lambda do |corrector| expr = node.loc.expression b = expr.begin_pos b -= key_delta.abs if key_delta < 0 range = Parser::Source::Range.new(expr.source_buffer, b, expr.end_pos) source = ' ' * [key_delta, 0].max + if enforced_style(node) == 'key' expr.source else key_source = key.loc.expression.source padded_separator = case enforced_style(node) when 'separator' spaced_separator(node) when 'table' space = ' ' * (max_key_width - key_source.length) if node.loc.operator.is?('=>') space + spaced_separator(node) else spaced_separator(node) + space end end key_source + padded_separator + value.loc.expression.source end corrector.replace(range, source) end end |
#on_hash(node) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/rubocop/cop/style/align_hash.rb', line 12 def on_hash(node) first_pair = node.children.first if [cop_config['EnforcedHashRocketStyle'], cop_config['EnforcedColonStyle']].include?('table') key_widths = node.children.map do |pair| key, _value = *pair key.loc.expression.source.length end @max_key_width = key_widths.max if first_pair && value_delta(nil, first_pair, @max_key_width) != 0 @column_deltas = {} convention(first_pair, :expression) end end node.children.each_cons(2) do |prev, current| @column_deltas = deltas(first_pair, prev, current, @max_key_width) convention(current, :expression) unless good_alignment? end end |