{"id":16432517,"url":"https://github.com/guzart/opie","last_synced_at":"2025-07-13T20:06:59.550Z","repository":{"id":56886933,"uuid":"85437274","full_name":"guzart/opie","owner":"guzart","description":"Operations API for Railway oriented programming in Ruby","archived":false,"fork":false,"pushed_at":"2018-01-27T03:48:39.000Z","size":40,"stargazers_count":3,"open_issues_count":3,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-04T14:01:56.390Z","etag":null,"topics":["operations","railway-oriented-programming","ruby","transactions"],"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/guzart.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-03-18T22:54:47.000Z","updated_at":"2020-08-31T04:39:00.000Z","dependencies_parsed_at":"2022-08-20T14:31:27.520Z","dependency_job_id":null,"html_url":"https://github.com/guzart/opie","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/guzart/opie","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/guzart%2Fopie","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/guzart%2Fopie/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/guzart%2Fopie/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/guzart%2Fopie/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/guzart","download_url":"https://codeload.github.com/guzart/opie/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/guzart%2Fopie/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":265198361,"owners_count":23726449,"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":["operations","railway-oriented-programming","ruby","transactions"],"created_at":"2024-10-11T08:43:38.898Z","updated_at":"2025-07-13T20:06:59.522Z","avatar_url":"https://github.com/guzart.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Opie\n\n[![Build Status](https://travis-ci.org/guzart/opie.svg?branch=master)](https://travis-ci.org/guzart/opie)\n[![codecov](https://codecov.io/gh/guzart/opie/branch/master/graph/badge.svg)](https://codecov.io/gh/guzart/opie)\n[![Code Climate](https://codeclimate.com/github/guzart/opie/badges/gpa.svg)](https://codeclimate.com/github/guzart/opie)\n[![Gem Version](https://badge.fury.io/rb/opie.svg)](https://badge.fury.io/rb/opie)\n\n**Opie gives you a simple API for creating Operations using the\n[Railsway oriented programming](https://vimeo.com/113707214) paradigm.**\n\n## API\n\nThe `Opie::Operation` API:\n  * `::step(Symbol) -\u003e void` indicates a method that is executed in the operation sequence\n  * `#success? -\u003e Boolean` indicates  whether the operation was successful\n  * `#failure? -\u003e Boolean` indicates  whether the operation was a failure\n  * `#failure -\u003e Opie::Failure | nil` the failure if the operation is a `failure?`, nil when it's a success\n  * `#failures -\u003e Array\u003cOpie::Failure\u003e | nil` an array with all failures\n  * `#output -\u003e * | nil` the operation's last step return value, nil when the operation fails\n\nInternal API:\n  * `#step_name(Any, Any?) -\u003e Any` the step signature. First argument is the input and the second argument is an optional context\n  * `#fail(error_type: Symbol, error_data: *) -\u003e Opie::Failure` used inside the steps to indicate that the operation has failed\n\nExecuting an operation:\n\n```ruby\ninput = { first_name: 'John', last_name: 'McClane', email: 'john@example.com' }\ncontext = { current_user: 'admin' }\n\nCreateUserOperation.(input, context)\n```\n\n_Tentative API_\n\n  * `::step(Array\u003cSymbol\u003e) -\u003e void` a series of methods to be called in parallel\n  * `::step(Opie::Step) -\u003e void` an enforcer of a step signature which helps to compose other steps\n  * `::failure(Symbol) -\u003e void` indicates a custom method name to handle failures\n\n## Usage\n\n**Simple Usage:**\n\n```ruby\n# Create an Operation for completing a Todo\nclass Todos::CompleteTodo \u003c Opie::Operation\n  step :find_todo\n  step :mark_as_complete\n\n  def find_todo(todo_id)\n    todo = Todo.find_by(id: todo_id)\n    return fail(:not_found, \"Could not find the Todo using id: #{todo_id}\") unless todo\n    todo\n  end\n\n  def mark_as_complete(todo)\n    success = todo.update(completed_at: Time.zone.now)\n    return fail(:update) unless success\n    todo\n  end\nend\n\nclass TodosController \u003c ApplicationController\n  def complete\n    # invoke the operation\n    result = Todos::CompleteTodo.(params[:id])\n    if result.success? # if #success?\n      render status: :created, json: result.output # use output\n    else\n      render status: :bad_request, json: { error: error_message(result.failure) } # otherwise use #failure\n    end\n  end\n\n  private\n\n  def error_message(failure)\n    case failure.type\n      when :not_found then failure.data\n      when :update then 'We were unable to make the changes to your todo'\n      else 'There was an unexpected error, sorry for the inconvenience'\n    end\n  end\nend\n```\n\n**Real world example:**\n\nImagine yourself in the context of a [habit tracker](https://github.com/isoron/uhabits), wanting to \nadd a new habit to track.\n\n```ruby\n# app/controllers/habits_controller.rb\n\nclass HabitsController \u003c ApplicationController\n  # POST /habits\n  def create\n    # run the `operation` – since it's a modification we can call it a `command`\n    result = People::AddHabit.(habit_params, operation_context)\n\n    # render response based on operation result\n    if result.success?\n      render status: :created, json: result.output\n    else\n      render_operation_failure(result.failure)\n    end\n  end\n\n  private\n\n  def render_operation_failure(failure)\n    render status: failure_http_status(failure.type), json: { errors: failure.data }\n  end\n\n  # the HTTP status depends on the error type, which separating the domain from the infrastructure\n  def failure_http_status(type)\n    case(type)\n    when :unauthorized then :unauthorized\n    when :validation then :unprocessable_entity \n    when :not_found then :not_found\n    else :server_error\n    end\n  end\n\n  # simulate parameters came from a Http request\n  def habit_params\n    {\n      person_id: 2,\n      name: 'Excercise',\n      description: 'Did you excercise for at least 15 minutes today?',\n      frequency: :three_times_per_week,\n      color: 'DeepPink'\n    }\n  end\n\n  def operation_context\n    { current_user: current_user }\n  end\nend\n```\n\nAnd now the code that defines the operation\n\n```ruby\n# application-wide dependencies container\nclass HabitTrackerContainer\n  extends Dry::Container::Mixin\n\n  register 'repositories.habit', HabitRepository.new\n  register 'repositories.person', PersonRepository.new\n  register 'service_bus', ServiceBus.new\nend\n\n# application-wide dependency injector\nImport = Dry::AutoInject(HabitTrackerContainer.new)\n\nmodule People\n  # we define a validation schema for our input\n  AddHabitSchema = Dry::Schema.Validation do\n    configure do\n      # custom predicate for frequency\n      def freq?(value)\n        [:weekly, :five_times_per_week, :four_times_per_week, :three_times_per_week].includes?(value)\n      end\n    end\n    \n    required(:person_id).filled(:int?, gt?: 0)\n    required(:name).filled(:str?)\n    required(:description).maybe(:str?)\n    required(:frequency).filled(:freq?)\n    required(:color).filled(:str?)\n  end\n\n  # the operation logic starts\n  class AddHabit \u003c Opie::Operation \n    # inject dependencies, more flexible than ruby's global namespace\n    include Import[\n      habit_repo: 'repositories.habit',\n      person_repo: 'repositories.person',\n      service_bus: 'service_bus'\n    ]\n\n    # first step receives ::call first argument, then the output of the step is the argument of the next step\n    step :authorize\n    step :validate\n    step :find_person\n    step :persist_habit\n    step :send_event\n\n    def authorize(params, context)\n      # Authorize using Pundit's policy api\n      return fail(:unauthorized) if HabitPolicy.new(context, Habit).add?\n      params\n    end\n\n    # receives the first input\n    def validate(params)\n      schema = AddHabitSchema.(params)\n      return fail(:validation, schema.errors) if schema.failure?\n      schema.output\n    end\n\n    # if it's valid then find the person (tenant)\n    def find_person(params)\n      person = person_repo.find(params[:person_id])\n      return fail(:repository, 'We could not find your account') unless person\n      params.merge(person: person)\n    end\n\n    # persist the new habit\n    def persist_habit(params)\n      new_habit = Entities::Habit.new(params)\n      habit_repo.create(new_habit)\n    rescue =\u003e error\n      fail(:persist_failed, error.message)\n    end\n\n    # notify the world\n    def send_event(habit)\n      event = Habits::CreatedEvent.new(habit.attributes)\n      service_bus.send(event)\n    rescue =\u003e error\n      fail(:event_failed, error)\n    end\n  end\nend\n```\n\n## Installation\n\nAdd this line to your application's Gemfile:\n\n```ruby\ngem 'opie'\n```\n\nAnd then execute:\n\n```bash\n$ bundle\n```\n\nOr install it yourself as:\n\n```bash\n$ gem install opie\n```\n\n## Development\n\nAfter checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests.\nYou 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\nthe version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for\nthe 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/guzart/opie.\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","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fguzart%2Fopie","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fguzart%2Fopie","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fguzart%2Fopie/lists"}