Class: MKBrut::Ops::AddI18nMessage

Inherits:
PrismParsingOp show all
Defined in:
lib/mkbrut/ops/add_i18n_message.rb

Instance Method Summary collapse

Methods inherited from BaseOp

dry_run=, dry_run?, #dry_run?, fileutils_args, #fileutils_args

Constructor Details

#initialize(project_root:, hash:) ⇒ AddI18nMessage

Returns a new instance of AddI18nMessage.



2
3
4
5
# File 'lib/mkbrut/ops/add_i18n_message.rb', line 2

def initialize(project_root:, hash:)
  @file = project_root / "app" / "config" / "i18n" / "en" / "2_app.rb"
  @hash = hash
end

Instance Method Details

#callObject



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
# File 'lib/mkbrut/ops/add_i18n_message.rb', line 7

def call
  if dry_run?
    puts "Would merge:\n#{@hash}\ninto #{@file}"
    return
  end
  parse_file!

  hash_node = @tree.value.statements.body.detect { it.is_a?(Prism::HashNode) }
  if !hash_node
    raise "'#{@file}' did not have a hash node, so we cannot insert a new i18n message"
  end

  # eval the source to get a real hash of the contents
  start_offset  = hash_node.location.start_offset
  end_offset    = hash_node.location.end_offset
  original_code = @source[start_offset...end_offset]
  original_hash = eval(original_code, binding, @file.to_s)

  new_hash = deep_merge(original_hash,@hash)

  formatted_hash = format_hash(new_hash)

  new_source = @source.dup
  new_source[start_offset...end_offset] = formatted_hash

  File.open(@file, "w") do |file|
    file.puts new_source
  end
end