On Fri, Dec 2, 2011 at 7:28 PM, Peter Vandenabeele
<peter / vandenabeele.com> wrote:
> On Fri, Dec 2, 2011 at 1:49 PM, Steve Klabnik <steve / steveklabnik.com>wrote:
>
>> Abstract base classes are silly in Ruby; why bother with that
>> inheritance? Just take advantage of duck typing.

> I was under the impression that it does make sense to have an abstract
> base class that has a number of generic methods and then derived classes:
> * add some specific methods
> * add some specific attributes
> * override some of the inherited methods

=> Template method pattern

> I have a specific example I was just implementing with an abstract
> base class for an "account" (think "bank account"). There are different
> derived classes, e.g. for simple money, but also for credits. Certain
> functions are generic (e.g. balance), but certain functions are specific
> (e.g. put funds on the account will use decimals for "money", but only
> accept integers for "credits"). I have put some demo code below.
>
> Very curious to hear how this design could be improved with duck typing.

Not really duck typing, but this is how template method could look in this case

class Account
  def initialize
    extend MonitorMixin
    @balance = 0
  end

  def balance
    synchronize do
      @balance
    end
  end

  def put(amount)
    ensure_proper_amount(amount)

    synchronize do
      @balance += amount
    end
  end

end

class MoneyAccount < Account
  def ensure_proper_amount(amount)
    raise "you can only put decimal amounts in a MoneyAccount" unless
      BigDecimal === amount
  end
end

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/