require 'rubypitaya/core/handler_base' module RubyPitaya class HandlerRouter def initialize() routes_path = Path::ROUTES_FILE_PATH handler_folder_paths = Path::Plugins::HANDLERS_FOLDER_PATHS + [Path::HANDLERS_FOLDER_PATH] import_routes_file(routes_path) handler_folder_paths.each do |handler_folder_path| import_handler_files(handler_folder_path) end import_routes_class import_handler_classes end def import_routes_file(routes_path) require routes_path end def import_routes_class routes_classes = ObjectSpace.each_object(RoutesBase.singleton_class).select do |klass| klass != RoutesBase end @routes = routes_classes.first.new end def import_handler_files(handler_folder_path) Gem.find_files("#{handler_folder_path}/*.rb").each { |path| require path } end def import_handler_classes handler_classes = ObjectSpace.each_object(HandlerBase.singleton_class).select do |klass| klass != HandlerBase end @handlers = handler_classes.map { |handler_class| handler_class.new } @handler_name_map = @handlers.map do |handler| handler_name = handler.class.to_s handler_name = @routes.get_new_handler_name(handler_name) handler_name = handler_name.split('::').last handler_name = handler_name[0].downcase + handler_name[1..-1] [handler_name, handler] end @handler_name_map = @handler_name_map.to_h end def call(handler_name, action_name, session, postman, redis, setup, config, bll, params) unless @handler_name_map.include?(handler_name) return { code: StatusCodes::CODE_HANDLER_NOT_FOUND, msg: "Handler #{handler_name} not founded" } end unless @handler_name_map[handler_name].methods.include?(action_name.to_sym) return { code: StatusCodes::CODE_ACTION_NOT_FOUND, msg: "Handler #{handler_name} action #{action_name} not founded" } end handler = @handler_name_map[handler_name] handler.bll = bll handler.redis = redis handler.setup = setup handler.config = config handler.params = params handler.session = session handler.postman = postman if !handler.class.authenticated_action_name?(action_name) handler.send(action_name) else if session.authenticated? handler.send(action_name) else return { code: StatusCodes::CODE_NOT_AUTHENTICATED, msg: 'Not authenticated', } end end end end end