{"id":15288820,"url":"https://github.com/gangelo/simple_command_dispatcher","last_synced_at":"2025-04-13T06:32:09.680Z","repository":{"id":56895679,"uuid":"71823988","full_name":"gangelo/simple_command_dispatcher","owner":"gangelo","description":"A Ruby Gem that dispatches SimpleCommands (simple_command gem) dynamically, so that API applications do not have to hard-code things like api modules and version numbers.","archived":false,"fork":false,"pushed_at":"2025-01-02T15:02:42.000Z","size":317,"stargazers_count":5,"open_issues_count":4,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-03-26T23:11:33.418Z","etag":null,"topics":["api","api-rest","rails","rails-api","rails-gem","ruby","ruby-on-rails"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gangelo.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-10-24T19:22:04.000Z","updated_at":"2024-08-03T13:04:00.000Z","dependencies_parsed_at":"2024-05-06T11:34:15.722Z","dependency_job_id":"4a7a3260-38ff-4c08-b3db-419213bf60bc","html_url":"https://github.com/gangelo/simple_command_dispatcher","commit_stats":null,"previous_names":[],"tags_count":21,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gangelo%2Fsimple_command_dispatcher","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gangelo%2Fsimple_command_dispatcher/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gangelo%2Fsimple_command_dispatcher/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gangelo%2Fsimple_command_dispatcher/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gangelo","download_url":"https://codeload.github.com/gangelo/simple_command_dispatcher/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248312144,"owners_count":21082638,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","api-rest","rails","rails-api","rails-gem","ruby","ruby-on-rails"],"created_at":"2024-09-30T15:53:18.657Z","updated_at":"2025-04-13T06:32:09.338Z","avatar_url":"https://github.com/gangelo.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![Ruby](https://github.com/gangelo/simple_command_dispatcher/actions/workflows/ruby.yml/badge.svg?refresh=6)](https://github.com/gangelo/simple_command_dispatcher/actions/workflows/ruby.yml)\n[![GitHub version](https://badge.fury.io/gh/gangelo%2Fsimple_command_dispatcher.svg?refresh=6)](https://badge.fury.io/gh/gangelo%2Fsimple_command_dispatcher)\n[![Gem Version](https://badge.fury.io/rb/simple_command_dispatcher.svg?refresh=6)](https://badge.fury.io/rb/simple_command_dispatcher)\n[![](https://ruby-gem-downloads-badge.herokuapp.com/simple_command_dispatcher?type=total)](http://www.rubydoc.info/gems/simple_command_dispatcher/)\n[![Documentation](http://img.shields.io/badge/docs-rdoc.info-blue.svg)](http://www.rubydoc.info/gems/simple_command_dispatcher/)\n[![Report Issues](https://img.shields.io/badge/report-issues-red.svg)](https://github.com/gangelo/simple_command_dispatcher/issues)\n[![License](http://img.shields.io/badge/license-MIT-yellowgreen.svg)](#license)\n\n# Q. simple_command_dispatcher - what is it?\n# A. It's a Ruby gem!!!\n\n## Overview\n__simple_command_dispatcher__ (SCD) allows you to execute __simple_command__ commands (and now _custom commands_ as of version 1.2.1) in a more dynamic way. If you are not familiar with the _simple_command_ gem, check it out [here][simple-command]. SCD was written specifically with the [rails-api][rails-api] in mind; however, you can use SDC wherever you would use simple_command commands.\n\n## Update as of Version 1.2.1\n### Custom Commands\nSCD now allows you to execute _custom commands_ (i.e. classes that do not prepend the _SimpleCommand_ module) by setting `Configuration#allow_custom_commands = true` (see the __Custom Commands__ section below for details).\n\n## Example\nThe below example is from a `rails-api` API that uses token-based authentication and services two mobile applications, identified as *__my_app1__* and *__my_app2__*, in this example.\n\nThis example assumes the following:\n\n* `application_controller` is a base class, inherited by all other controllers. The `#authenticate_request` method is called for every request in order to make sure the request is authorized (`before_action :authenticate_request`).\n* `request.headers` will contain the authorization token to authorize all requests (`request.headers[\"Authorization\"]`)\n* This application uses the following folder structure to manage its _simple_command_ commands:\n\n![N|Solid](https://cldup.com/1UeyWzOLic.png)\n\nCommand classes (and the modules they reside under) are named *__according to their file name and respective location within the above folder structure__*; for example, the command class defined in the `/api/my_app1/v1/authenticate_request.rb` file would be defined in this manner:\n\n```ruby\n# /api/my_app1/v1/authenticate_request.rb\n\nmodule Api\n   module MyApp1\n      module V1\n         class AuthenticateRequest\n         end\n     end\n   end\nend\n```\n\nLikewise, the command class defined in the `/api/my_app2/v2/update_user.rb` file would be defined in this manner, and so on:\n\n```ruby\n# /api/my_app2/v2/update_user.rb\n\nmodule Api\n   module MyApp2\n      module V2\n         class UpdateUser\n         end\n     end\n   end\nend\n```\n\nThe __routes used in this example__, conform to the following format: `\"/api/[app_name]/[app_version]/[controller]\"` where `[app_name]` = the _application name_,`[app_version]` = the _application version_, and `[controller]` = the _controller_; therefore, running `$ rake routes` for this example would output the following sample route information:\n\n\n| Prefix        | Verb | URI Pattern | Controller#Action |\n|-------------:|:-------------|:------------------|:------------------|\n| api_my_app1_v1_user_authenticate | POST  | /api/my_app1/v1/user/authenticate(.:format) | api/my_app1/v1/authentication#create |\n| api_my_app1_v2_user_authenticate | POST  | /api/my_app1/v2/user/authenticate(.:format) | api/my_app1/v2/authentication#create |\n| api_my_app2_v1_user_authenticate | POST  | /api/my_app2/v1/user/authenticate(.:format) | api/my_app2/v1/authentication#create |\n| api_my_app2_v2_user              | PATCH | /api/my_app2/v2/users/:id(.:format)         | api/my_app2/v2/users#update |\n|                                  | PUT   | /api/my_app2/v2/users/:id(.:format)         | api/my_app2/v2/users#update |\n\n\n### Request Authentication Code Snippet\n\n```ruby\n# /config/initializers/simple_command_dispatcher.rb\n\n# See: http://pothibo.com/2013/07/namespace-stuff-in-your-app-folder/\n\n=begin\n# Uncomment this code if you want to namespace your commands in the following manner, for example:\n#\n#   class Api::MyApp1::V1::AuthenticateRequest; end\n#\n# As opposed to this:\n#\n#   module Api\n#      module MyApp1\n#         module V1\n#            class AuthenticateRequest\n#            end\n#         end\n#     end\n#   end\n#\nmodule Helpers\n   def self.ensure_namespace(namespace, scope = \"::\")\n      namespace_parts = namespace.split(\"::\")\n\n      namespace_chain = \"\"\n\n      namespace_parts.each { | part |\n         namespace_chain = (namespace_chain.empty?) ? part : \"#{namespace_chain}::#{part}\"\n         eval(\"module #{scope}#{namespace_chain}; end\")\n      }\n   end\nend\n\nHelpers.ensure_namespace(\"Api::MyApp1::V1\")\nHelpers.ensure_namespace(\"Api::MyApp1::V2\")\nHelpers.ensure_namespace(\"Api::MyApp2::V1\")\nHelpers.ensure_namespace(\"Api::MyApp2::V2\")\n=end\n\n# simple_command_dispatcher creates commands dynamically; therefore we need\n# to make sure the namespaces and command classes are loaded before we construct and\n# call them. The below code traverses the 'app/api' and all subfolders, and\n# autoloads them so that we do not get any NameError exceptions due to\n# uninitialized constants.\nRails.application.config.to_prepare do\n   path = Rails.root + \"app/api\"\n   ActiveSupport::Dependencies.autoload_paths -= [path.to_s]\n\n   reloader = ActiveSupport::FileUpdateChecker.new [], path.to_s =\u003e [:rb] do\n      ActiveSupport::DescendantsTracker.clear\n      ActiveSupport::Dependencies.clear\n\n      Dir[path + \"**/*.rb\"].each do |file|\n         ActiveSupport.require_or_load file\n      end\n   end\n\n   Rails.application.reloaders \u003c\u003c reloader\n   ActionDispatch::Reloader.to_prepare { reloader.execute_if_updated }\n   reloader.execute\nend\n\n# Optionally set our configuration setting to allow\n# for custom command execution.\nSimpleCommand::Dispatcher.configure do |config|\n   config.allow_custom_commands = true\nend\n```\n\n```ruby\n# /app/controllers/application_controller.rb\n\nrequire 'simple_command_dispatcher'\n\nclass ApplicationController \u003c ActionController::API\n   before_action :authenticate_request\n   attr_reader :current_user\n\n   protected\n\n   def get_command_path\n      # request.env['PATH_INFO'] could return any number of paths. The important\n      # thing (in the case of our example), is that we get the portion of the\n      # path that uniquely identifies the SimpleCommand we need to call; this\n      # would include the application, the API version and the SimpleCommand\n      # name itself.\n      command_path = request.env['PATH_INFO'] # =\u003e \"/api/[app name]/v1/[action]”\n      command_path = command_path.split('/').slice(0,4).join('/') # =\u003e \"/api/[app name]/v1/\"\n   end\n\n   private\n\n   def authenticate_request\n      # The parameters and options we are passing to the dispatcher, wind up equating\n      # to the following: Api::MyApp1::V1::AuthenticateRequest.call(request.headers).\n      # Explaination: @param command_modules (e.g. path, \"/api/my_app1/v1/\"), in concert with @param\n      # options { camelize: true }, is transformed into \"Api::MyApp1::V1\" and prepended to the\n      # @param command, which becomes \"Api::MyApp1::V1::AuthenticateRequest.\" This string is then\n      # simply constantized; #call is then executed, passing the @param command_parameters\n      # (e.g. request.headers, which contains [\"Authorization\"], out authorization token).\n      # Consequently, the correlation between our routes and command class module structure\n      # was no coincidence.\n      command = SimpleCommand::Dispatcher.call(:AuthenticateRequest, get_command_path, { camelize: true}, request.headers)\n      if command.success?\n         @current_user = command.result\n      else\n         render json: { error: 'Not Authorized' }, status: 401\n      end\n    end\nend\n```\n\n## Custom Commands\n\nAs of __Version 1.2.1__ simple_command_dispatcher (SCD) allows you to execute _custom commands_ (i.e. classes that do not prepend the _SimpleCommand_ module) by setting `Configuration#allow_custom_commands = true`.\n\nIn order to execute _custom commands_, there are three (3) requirements:\n   1. Create a _custom command_. Your _custom command_ class must expose a public `::call` class method.\n   2. Set the `Configuration#allow_custom_commands` property to `true`.\n   3. Execute your _custom command_ by calling the `::call` class method.\n\n### Custom Command Example\n\n#### 1. Create a Custom Command\n```ruby\n# /api/my_app/v1/custom_command.rb\n\nmodule Api\n   module MyApp\n         module V1\n\n            # This is a custom command that does not prepend SimpleCommand.\n            class CustomCommand\n\n               def self.call(*args)\n                  command = self.new(*args)\n                  if command\n                     command.send(:execute)\n                  else\n                     false\n                  end\n               end\n\n               private\n\n               def initialize(params = {})\n                  @param1 = params[:param1]\n               end\n\n               private\n\n               attr_accessor :param1\n\n               def execute\n                  if (param1 == :param1)\n                     return true\n                  end\n\n                  return false\n               end\n            end\n\n      end\n   end\nend\n```\n#### 2. Set the `Configuration#allow_custom_commands` property to `true`\n```ruby\n# In your rails, rails-api app, etc...\n# /config/initializers/simple_command_dispatcher.rb\n\nSimpleCommand::Dispatcher.configure do |config|\n    config.allow_custom_commands = true\nend\n```\n\n#### 3. Execute your _Custom Command_\nExecuting your _custom command_ is no different than executing a __SimpleCommand__ command with the exception that you must properly handle the return object that results from calling your _custom command_; being a _custom command_, there is no guarantee that the return object will be the command object as is the case when calling a SimpleCommand command.\n```ruby\n# /app/controllers/some_controller.rb\n\nrequire 'simple_command_dispatcher'\n\nclass SomeController \u003c ApplicationController::API\n   public\n\n   def some_api\n      success = SimpleCommand::Dispatcher.call(:CustomCommand, get_command_path, { camelize: true}, request.headers)\n      if success\n         # Do something...\n      else\n         # Do something else...\n      end\n    end\nend\n```\n\n## Installation\n\nAdd this line to your application's Gemfile:\n\n```ruby\ngem 'simple_command_dispatcher'\n```\n\nAnd then execute:\n\n    $ bundle\n\nOr install it yourself as:\n\n    $ gem install simple_command_dispatcher\n\n## Usage\n\nSee the example above.\n\n## Development\n\nAfter checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.\n\nTo install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).\n\n## Contributing\n\nBug reports and pull requests are welcome on GitHub at https://github.com/gangelo/simple_command_dispatcher. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.\n\n\n## License\n\nThe gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).\n\n   [simple-command]: \u003chttps://rubygems.org/gems/simple_command\u003e\n   [rails-api]: \u003chttps://rubygems.org/gems/rails-api\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgangelo%2Fsimple_command_dispatcher","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgangelo%2Fsimple_command_dispatcher","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgangelo%2Fsimple_command_dispatcher/lists"}