Sha256: f9deb18087ede69ec1902654f0e2ffee0cbbe834fb9644d3ba1383c45713b8d3

Contents?: true

Size: 1.52 KB

Versions: 3

Compression:

Stored size: 1.52 KB

Contents

# frozen_string_literal: true
require 'rails/generators/named_base'
require_relative 'core'

module Graphql
  module Generators
    # TODO: What other options should be supported?
    #
    # @example Generate a `Relay::Mutation` by name
    #     rails g graphql:mutation CreatePostMutation
    class MutationGenerator < Rails::Generators::Base
      include Core

      desc "Create a Relay mutation by name"
      source_root File.expand_path('../templates', __FILE__)

      argument :name, type: :string

      def initialize(args, *options) #:nodoc:
        # Unfreeze name in case it's given as a frozen string
        args[0] = args[0].dup if args[0].is_a?(String) && args[0].frozen?
        super

        assign_names!(name)
      end

      attr_reader :file_name, :mutation_name, :field_name

      def create_mutation_file
        create_mutation_root_type
        template "mutation.erb", "#{options[:directory]}/mutations/#{file_name}.rb"

        sentinel = /name "Mutation"\s*\n/m
        in_root do
          gsub_file "#{options[:directory]}/types/mutation_type.rb", /  \# TODO\: Add Mutations as fields\s*\n/m, ""
          inject_into_file "#{options[:directory]}/types/mutation_type.rb", "  field :#{field_name}, Mutations::#{mutation_name}.field\n", after: sentinel, verbose: false, force: false
        end
      end

      private

      def assign_names!(name)
        @field_name = name.camelize(:lower)
        @mutation_name = name.camelize(:upper)
        @file_name = name.camelize.underscore
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
graphql-1.8.0.pre1 lib/generators/graphql/mutation_generator.rb
graphql-1.7.6 lib/generators/graphql/mutation_generator.rb
graphql-1.7.5 lib/generators/graphql/mutation_generator.rb