class GraphQL::Upgrader::MutationResolveProcToMethodTransform

Public Class Methods

new(proc_name: "resolve") click to toggle source

@param proc_name [String] The name of the proc to be moved to `def self.#{proc_name}`

# File lib/graphql/upgrader/member.rb, line 347
def initialize(proc_name: "resolve")
  @proc_name = proc_name
end

Public Instance Methods

apply(input_text) click to toggle source

TODO dedup with ResolveProcToMethodTransform

# File lib/graphql/upgrader/member.rb, line 352
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)
    proc_body = input_text[named_proc_processor.proc_body_start..named_proc_processor.proc_body_end]
    method_defn_indent = " " * named_proc_processor.proc_defn_indent

    obj_arg_name, args_arg_name, ctx_arg_name = resolve_proc_processor.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[named_proc_processor.proc_defn_start..named_proc_processor.proc_defn_end] = method_defn
  end
  input_text
end