envato / double_entry

A double-entry accounting system for Ruby applications.
https://rubygems.org/gems/double_entry
MIT License
422 stars 68 forks source link

Allow validation on transfer definition #191

Closed adis-io closed 2 years ago

adis-io commented 4 years ago

For my project I needed some sort of additional check when I defined transfers.

Something like this:

transfers.define(from: :savings,  to: :checking, code: :withdraw) do |from, to|
  if from.scope.blocked?
    fail DoubleEntry::TransferNotAllowed, 'user is blocked'
  end
end

I monkey patched gem and would like to make a PR if you think it's worth to have.

Here's my monkey patch:

# frozen_string_literal: true

module OverrideDefineMethod
  def define(attributes, &block)
    attributes.merge!(block: block) if block_given?
    super(attributes)
  end

  def find!(from_account, to_account, code)
    transfer = super
    transfer.block.call(from_account, to_account) if transfer.block
    transfer
  end
end

module OverrideTransferInitializer
  attr_reader :block

  def initialize(attributes)
    @block = attributes[:block]
    super(attributes)
  end
end

DoubleEntry::Transfer::Set.prepend OverrideDefineMethod
DoubleEntry::Transfer.prepend OverrideTransferInitializer
ricobl commented 2 years ago

Thanks for your suggestion @adis-io!

It appears that this might end up mixing business concerns with the gem. Did you consider having an abstraction layer on the application code instead?

ricobl commented 2 years ago

I'll close this as we're making an effort to keep things tidy, feel free to share your thoughts but at the moment we believe this doesn't belong in the gem. Thanks again @adis-io!