|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require "erb" |
| 4 | +require "dry/files" |
| 5 | +require_relative "../../errors" |
| 6 | + |
| 7 | +module Hanami |
| 8 | + module CLI |
| 9 | + module Generators |
| 10 | + module App |
| 11 | + # @since 2.2.0 |
| 12 | + # @api private |
| 13 | + class Operation |
| 14 | + # @since 2.2.0 |
| 15 | + # @api private |
| 16 | + def initialize(fs:, inflector:, out: $stdout) |
| 17 | + @fs = fs |
| 18 | + @inflector = inflector |
| 19 | + @out = out |
| 20 | + end |
| 21 | + |
| 22 | + # @since 2.2.0 |
| 23 | + # @api private |
| 24 | + def call(app, key, slice) |
| 25 | + context = OperationContext.new(inflector, app, slice, key) |
| 26 | + |
| 27 | + if slice |
| 28 | + generate_for_slice(context, slice) |
| 29 | + else |
| 30 | + generate_for_app(context) |
| 31 | + end |
| 32 | + end |
| 33 | + |
| 34 | + private |
| 35 | + |
| 36 | + attr_reader :fs, :inflector, :out |
| 37 | + |
| 38 | + def generate_for_slice(context, slice) |
| 39 | + slice_directory = fs.join("slices", slice) |
| 40 | + raise MissingSliceError.new(slice) unless fs.directory?(slice_directory) |
| 41 | + |
| 42 | + if context.namespaces.any? |
| 43 | + fs.mkdir(directory = fs.join(slice_directory, context.namespaces)) |
| 44 | + fs.write(fs.join(directory, "#{context.name}.rb"), t("nested_slice_operation.erb", context)) |
| 45 | + else |
| 46 | + fs.mkdir(directory = fs.join(slice_directory)) |
| 47 | + fs.write(fs.join(directory, "#{context.name}.rb"), t("top_level_slice_operation.erb", context)) |
| 48 | + out.puts(" Note: We generated a top-level operation. To generate into a directory, add a namespace: `my_namespace.#{context.name}`") |
| 49 | + end |
| 50 | + end |
| 51 | + |
| 52 | + def generate_for_app(context) |
| 53 | + if context.namespaces.any? |
| 54 | + fs.mkdir(directory = fs.join("app", context.namespaces)) |
| 55 | + fs.write(fs.join(directory, "#{context.name}.rb"), t("nested_app_operation.erb", context)) |
| 56 | + else |
| 57 | + fs.mkdir(directory = fs.join("app")) |
| 58 | + out.puts(" Note: We generated a top-level operation. To generate into a directory, add a namespace: `my_namespace.#{context.name}`") |
| 59 | + fs.write(fs.join(directory, "#{context.name}.rb"), t("top_level_app_operation.erb", context)) |
| 60 | + end |
| 61 | + end |
| 62 | + |
| 63 | + def template(path, context) |
| 64 | + require "erb" |
| 65 | + |
| 66 | + ERB.new( |
| 67 | + File.read(__dir__ + "/operation/#{path}") |
| 68 | + ).result(context.ctx) |
| 69 | + end |
| 70 | + |
| 71 | + alias_method :t, :template |
| 72 | + end |
| 73 | + end |
| 74 | + end |
| 75 | + end |
| 76 | +end |
0 commit comments