Class: GraphQL::Upgrader::MutationResolveProcToMethodTransform

Inherits:
Transform
  • Object
show all
Defined in:
lib/graphql/upgrader/member.rb

Instance Method Summary collapse

Methods inherited from Transform

#apply_processor, #normalize_type_expression, #reindent_lines, #trim_lines, #underscorize

Constructor Details

#initialize(proc_name: "resolve") ⇒ MutationResolveProcToMethodTransform

Returns a new instance of MutationResolveProcToMethodTransform

Parameters:

  • proc_name (String)

    The name of the proc to be moved to def self.#{proc_name}



364
365
366
# File 'lib/graphql/upgrader/member.rb', line 364

def initialize(proc_name: "resolve")
  @proc_name = proc_name
end

Instance Method Details

#apply(input_text) ⇒ Object

TODO dedup with ResolveProcToMethodTransform



369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# File 'lib/graphql/upgrader/member.rb', line 369

def apply(input_text)
  if input_text =~ /GraphQL::Relay::Mutation\.define/
    named_proc_processor = apply_processor(input_text, ProcToClassMethodTransform::NamedProcProcessor.new(@proc_name))
    resolve_proc_processor = apply_processor(input_text, ResolveProcToMethodTransform::ResolveProcProcessor.new)

    named_proc_processor.proc_to_method_sections.zip(resolve_proc_processor.resolve_proc_sections).reverse.each do |pair|
      proc_to_method_section, resolve_proc_section = *pair
      proc_body = input_text[proc_to_method_section.proc_body_start..proc_to_method_section.proc_body_end]
      method_defn_indent = " " * proc_to_method_section.proc_defn_indent

      obj_arg_name, args_arg_name, ctx_arg_name = resolve_proc_section.proc_arg_names
      # This is not good, it will hit false positives
      # Should use AST to make this substitution
      if obj_arg_name != "_"
        proc_body.gsub!(/([^\w:.]|^)#{obj_arg_name}([^\w:]|$)/, '\1object\2')
      end
      if ctx_arg_name != "_"
        proc_body.gsub!(/([^\w:.]|^)#{ctx_arg_name}([^\w:]|$)/, '\1context\2')
      end

      method_defn = "def #{@proc_name}(**#{args_arg_name})\n#{method_defn_indent}  #{proc_body}\n#{method_defn_indent}end\n"
      method_defn = trim_lines(method_defn)
      # Update usage of args keys
      method_defn = method_defn.gsub(/#{args_arg_name}(?<method_begin>\.key\?\(?|\[)["':](?<arg_name>[a-zA-Z0-9_]+)["']?(?<method_end>\]|\))?/) do
        method_begin = $~[:method_begin]
        arg_name = underscorize($~[:arg_name])
        method_end = $~[:method_end]
        "#{args_arg_name}#{method_begin}:#{arg_name}#{method_end}"
      end
      # replace the proc with the new method
      input_text[proc_to_method_section.proc_defn_start..proc_to_method_section.proc_defn_end] = method_defn
    end
  end
  input_text
end