Skip to content

mtkachenk0/service_dsl

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

ServiceDSL

🧩 A lightweight, expressive DSL for writing service objects in Ruby.

Define business logic in a clean, readable structure using expects, promises, and lifecycle blocks (prepare, validate, perform) with context-based control flow.


✨ Features

  • expects and promises for defining input/output contracts
  • prepare, validate, perform block hooks
  • ctx.fail!(message, with: SomeError) for graceful failure
  • ServiceDSL::Result object with success?, errors, and dynamic access
  • Minimal dependencies, works with any Ruby project

πŸš€ Usage

class CreateUser
  include ServiceDSL

  expects :name, @email
  promises :user

  prepare do |ctx|
    @email = ctx.email.strip.downcase
  end

  validate do |ctx|
    ctx.fail!("Email invalid", with: ArgumentError) unless ctx.email.include?("@")
    raise "Name cannot be blank" if ctx.name.to_s.strip.empty? # any errors are caught by ServiceDSL
  end

  perform do |ctx|
    ctx.user = create_user
  end

  private

  def create_user
    User.create!(name: context.name, email: @email) # context is available
  end
end

result = CreateUser.call(name: "Max", email: "  max@example.com ")

if result.success?
  puts result.user
else
  puts result.errors.join(", ")
end

API Reference

DSL Macros

  • expects :key1, :key2 β€” required input keys
  • promises :key β€” required outputs
  • prepare { |ctx| } β€” run before validation
  • validate { |ctx| } β€” run before perform; can raise or call ctx.fail!
  • perform do |ctx| end β€” main logic block

Context Helpers

ctx.key # β€” access expected input

ctx.key = value # β€” set promised output

ctx.fail!("msg", with: SomeErrorClass) # β€” stop andmark as failed

Result Object

result.success? # => true/false
result.errors   # => ["Email invalid"]
result.user     # => dynamic access to promised values

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages