# frozen_string_literal: true require 'erb' require 'fileutils' require_relative 'exe_helpers' require 'colorize' module LeapSalesforce # Generators for creating code module Generator # @param [String] filename Relative filename to this file # @param [String] folder Folder where templates are stored (for external gems) # @return [String] Location of template file def template_loc(filename, folder: nil) template_dir = folder || __dir__ File.join(template_dir, 'templates', filename) end # @param [String] filename Relative filename to this file # @param [Binding] binding Binding object used for ERB variables # @param [String] folder Folder where templates are stored (for external gems) # @return [String] Interpreted file after calculating ERB for template file passed def read_template(filename, binding, folder: nil) ERB.new(File.read(template_loc(filename, folder: folder))).result(binding) end # Generate file creating necessary folder if necessary # @param [String] filename Name of file to generate # @param [String] content Content to put within file def generate_file(filename, content, overwrite: true) FileUtils.mkdir_p File.dirname filename unless File.directory? File.dirname(filename) action = if File.exist?(filename) return puts "File '#{filename}' already exists, skipping...".colorize :red unless overwrite 'Updated' else 'Created' end File.write filename, content puts "\u2713 #{action} #{filename}".colorize :green end # @example Create a spec_helper file and test file in spec folder # generate_files [ { spec: [ 'spec_helper.rb', 'limit_spec.rb' ] } ] # @param [Hash, Array] list_of_files Hash of files to generate for def generate_files(binding, list_of_files, folder: nil) return create_inner_file(folder, list_of_files, binding) unless list_of_files.respond_to? :each list_of_files.each do |item| if item.is_a? Hash # Go one level deeper item.each do |inner_folder, sub_files| inner_folder = inner_folder.to_s current_folder = folder ? File.join(folder, inner_folder) : inner_folder generate_files binding, sub_files, folder: current_folder end else create_inner_file folder, item, binding end end end def create_inner_file(folder, name, binding) item = name.to_s path = folder ? File.join(folder, item) : item generate_from_template path, binding end # Generate file from template # @param [String] template_name Path to file with templates folder to use as template # @param [Binding] binding Binding object used for ERB variables def generate_from_template(template_name, binding) content = read_template "#{template_name}.erb", binding generate_file template_name, content, overwrite: false end end end