module Eco module API class UseCases # Basic class to manage InputOuput for usecases class BaseIO < BaseCase @types = BaseCase.types class << self def input_required?(type) !valid_type?(type) || [:import, :sync].include?(type) end def people_required?(type) !valid_type?(type) || [:filter, :transform, :sync, :error_handler, :export].include?(type) end end attr_reader :input, :people, :session, :options attr_reader :type attr_accessor :output # @param type [Symbol] a valid type (among `self.class.types`) # @param input [Eco::API::Common::People::Entries, Eco::API::Organization::People] the input data of reference. # @param people [Eco::API::Organization::People] people object. # @param session [Eco::API:Session] # @param options [Hash] hash with symbol keys (i.e. behaviour modifiers, cli trackers, filters, etc.) def initialize(type: nil, input: nil, people: nil, session:, options: {}, validate: true) @output = nil self.type = type if type if self.type && validate validate_args(input: input, people: people, session: session, options: options) end @input = input @people = people @session = session @options = options end # @param value [Symbol] a valid type (among `self.class.types`) def type=(value) self.class.validate_type(value) @type = value end # Helper to obtain an `BaseIO` objcect from any child class. # @return [Eco::API::UseCases::BaseIO] def base kargs = params(keyed: true).merge(type: self.type).slice(:type, :input, :people, :session, :options) Eco::API::UseCases::BaseIO.new(**kargs) end # @see Eco::API::UseCases::BaseIO#initialize # @return [Eco::API::UseCases::BaseIO] def new(**kargs) default = { type: self.type, input: self.input, people: self.people, session: self.session, options: self.options, validate: true }.merge(kargs) self.class.new(**default.merge(kargs)) end # Helper to build a `Hash` of symbol keys or `Array` with params to do callbacks. def params(keyed: false, all: false) kargs = {} kargs.merge!(input: input) if input_required? || all kargs.merge!(people: people) if people_required? || all kargs.merge!(session: session, options: options) keyed ? kargs : kargs.values end private def validate_args(input:, people:, session:, options:) case when !session.is_a?(Eco::API::Session) raise "A UseCase needs a Session object. Given: #{session}" when input_required? && !input raise "UseCase of type '#{type}' requires a valid input. None given" when people_required? && !people.is_a?(Eco::API::Organization::People) raise "UseCase of type '#{type}' requires a People object. Given: #{people}" when !options || (options && !options.is_a?(Hash)) raise "To inject dependencies via ':options' it should be a Hash object. Given: #{options}" end true end def input_required? self.class.input_required?(type) end def people_required? self.class.people_required?(type) end end end end end