Class: GraphQL::Upgrader::NameTransform

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

Overview

Remove name "Something" if it is redundant with the class name. Or, if it is not redundant, move it to graphql_name "Something".

Instance Method Summary collapse

Methods inherited from Transform

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

Instance Method Details

#apply(transformable) ⇒ Object



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/graphql/upgrader/member.rb', line 131

def apply(transformable)
  last_type_defn = transformable
    .split("\n")
    .select { |line| line.include?("class ") || line.include?("module ")}
    .last

  if last_type_defn && (matches = last_type_defn.match(/(class|module) (?<type_name>[a-zA-Z_0-9:]*)( <|$)/))
    type_name = matches[:type_name]
    # Get the name without any prefixes or suffixes
    type_name_without_the_type_part = type_name.split('::').last.gsub(/Type$/, '')
    # Find an overridden name value
    if matches = transformable.match(/ name ('|")(?<overridden_name>.*)('|")/)
      name = matches[:overridden_name]
      if type_name_without_the_type_part != name
        # If the overridden name is still required, use `graphql_name` for it
        transformable = transformable.sub(/ name (.*)/, ' graphql_name \1')
      else
        # Otherwise, remove it altogether
        transformable = transformable.sub(/\s+name ('|").*('|")/, '')
      end
    end
  end

  transformable
end