module Eco class CLI class Config class UseCases attr_reader :core_config def initialize(core_config:) @core_config = core_config @linked_opt_cases = {} end # Integrates a usecase to the command line # @param option_case [String] the command line option to invoke the usecase # @param type [Symbol] the type of usecase # @param case_name [String, nil] the name of the usecase as defined def add(option_case, type, case_name: nil) Eco::API::UseCases::UseCase.validate_type(type) unless callback = block_given?? Proc.new : nil raise "You must specify a valid 'case_name' when no block is provided" unless case_name raise "'case_name' expected to be a String. Given: #{case_name.class}" unless case_name.is_a?(String) end @linked_opt_cases[option_case] = { type => { casename: case_name, callback: callback } } self end # Scopes/identifies which usecases are being invoked from the command line # @param io [Eco::API::UseCases::BaseIO] the input/output object # @return [Hash] where keys are cases and values a `Hash` with `option` String and `callback` def active(io:) return @active_cases unless !@active_cases @active_cases = {}.tap do |opt_cases| @linked_opt_cases.each do |option_case, types| types.each do |type, data| if SCR.get_arg(option_case) usecase = nil if case_name = data[:casename] usecase = io.session.usecases.case(case_name, type: type) end if callback = data[:callback] unless usecase # identify usecase usecase = callback.call(*io.params) unless usecase.is_a?(Eco::API::UseCases::UseCase) msg = "When adding a usecase, without specifying 'case_name:', " msg += "the block that integrates usecase for cli option '#{option_case}'" msg += " must return an Eco::API::UseCases::UseCase object. It returns #{usecase.class}" raise msg end end end if usecase opt_cases[usecase] = { option: option_case, callback: data[:callback] } end end end end end end def process(io:) unless io && io.is_a?(Eco::API::UseCases::BaseIO) raise "You need to provide Eco::API::UseCases::BaseIO object. Given: #{io.class}" end processed = false active(io: io).each do |usecase, data| raise "Something went wrong when scoping active cases" unless data processed = true params = io.params(keyed: true).merge(type: usecase.type) #if (!io.people || io.people.empty?) && io.class.people_required?(type) # params.merge!(people: core_config.people(io: io)) #end io.new(**params) if callback = data[:callback] callback.call(*io.params) end usecase.launch(io: io) end processed end end end end end