# frozen_string_literal: true require 'pastel' require 'ostruct' require 'active_support/inflector' require_relative '../../command' module Sumcli module Commands class Add class Endpoint < Sumcli::Command ENDPOINT_PATH = 'api/endpoints' MODELS_PATH = 'app/models' ENTITIES_PATH = 'api/entities' TESTS_PATH = 'spec/api' TEMPLATES_PATH = File.expand_path('../../templates/add/endpoint', __dir__) def initialize(name, method, route, options) @name = name @method = method @route = route @options = options @variables = OpenStruct.new(name: @name, route: @route, method: @method) end def execute(input: $stdin, output: $stdout) unless File.file?(".sumcli") pastel = Pastel.new output.puts pastel.red("ERROR!\nYou are no in a sumcli app directory.") output.puts <<-OUT.strip You can execute #{pastel.green('sumcli help new')} to get more info. OUT return end create_entity unless File.file?("#{ENTITIES_PATH}/#{@name.underscore}.rb") create_test unless File.file?("#{TESTS_PATH}/#{@name.underscore}.rb") create_endpoint unless File.file?("#{ENDPOINT_PATH}/#{@name.underscore}.rb") inject_route unless @method.nil? end def inject_mount generator.inject_into_file("#{ENDPOINT_PATH}/base.rb", after: "# APIs\n") do <<-RB mount API::#{@name.capitalize} RB end end def inject_route generator.inject_into_file("#{ENDPOINT_PATH}/#{@name.underscore}.rb", after: "# ENDPOINTS\n") do <<-RB desc 'Describe your endpoint' params do # requires :id, type: Integer end #{@method.downcase} '#{@route}' do # write code here.. end RB end end def create_test generator.copy_file( "#{TEMPLATES_PATH}/test.rb.erb", "#{TESTS_PATH}/#{@name.underscore}_spec.rb", context: @variables ) end def create_entity generator.copy_file( "#{TEMPLATES_PATH}/entity.rb.erb", "#{ENTITIES_PATH}/#{@name.underscore}.rb", context: @variables ) end def create_endpoint generator.copy_file( "#{TEMPLATES_PATH}/new.rb.erb", "#{ENDPOINT_PATH}/#{@name.underscore}.rb", context: @variables ) inject_mount end def create_model generator.copy_file( "#{TEMPLATES_PATH}/model.rb.erb", "#{MODELS_PATH}/#{@name.underscore}.rb", context: @variables ) end end end end end