# frozen_string_literal: true require 'erb' require 'fileutils' require_relative 'exe_helpers' module LeapSalesforce # Generators for creating code module Generator # @param [String] filename Relative filename to this file # @param [Binding] binding Binding object used for ERB variables # @return [String] Interpreted file after calculating ERB for template file passed def read_template(filename, binding) ERB.new(File.read(File.join(__dir__, 'templates', filename))).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) return puts "File '#{filename}' already exists, skipping..." if (File.exist?(filename) && !overwrite) File.write filename, content puts "Created file at #{filename}" end # @example Create a spec_helper file and test file in spec folder # generate_files [ { spec: [ 'spec_helper.rb', 'limit_spec.rb' ] } ] # @param [Hash] 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