Appendix D. Account Example in Ruby

This rendition comes from Steen Lehmann.

require 'osx/cocoa'

#!/usr/bin/env ruby
# Lean Architecture example in Ruby -
# with ContextAccessor

# Module that can be mixed in to any class
# that needs access to the current context. It is
# implemented as a thread-local variable.

module ContextAccessor
  def context
    Thread.current[:context]
  end

  def context=(ctx)
    Thread.current[:context] = ctx
  end

  def execute_in_context
    old_context = self.context
    self.context = self
    yield
    self.context = old_context
  end
end
#
# This is the base class (common code) for all
# Account domain classes.
#

class Account
  attr_reader :account_id, :balance

  def initialize(account_id)
    @account_id = account_id
    @balance = 0
  end

  def decreaseBalance(amount)
    raise "Bad argument to withdraw" if amount < 0
    raise "Insufficient funds" if amount > balance
    @balance -= amount
  end

  def increaseBalance(amount)
    @balance += amount
  end

  def update_log(msg, date, amount)
    puts "Account: #{inspect}, #{msg}, \ #{date.to_s},
       #{amount}"
  end

  def self.find(account_id)
    @@store ||= Hash.new
    return @@store[account_id] if @@store.has_key?
          account_id

    if :savings == account_id
      account = SavingsAccount.new(account_id)
      account.increaseBalance(100000)
    elsif :checking == account_id
      account = CheckingAccount.new(account_id)
    else
      account = Account.new(account_id)
    end
    @@store[account_id] = account
    account
  end
end
# This module is the methodless role type. Since # we don't really use types to declare identifiers, # it's kind ...

Get Lean Architecture for Agile Software Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.