Module: QuacksLike

Defined in:
lib/quacks_like.rb

Overview

QuacksLike

QuacksLike is a tiny gem intended to push people towards using duck typing instead of static typing.

Usage

def some_method(an_argument)
  case an_argument
  when quacks_like?(:to_i)                 # responds_to?(:to_i)
    do_something_with an_argument.to_i
  when quacks_like?(:foo, :bar)            # responds_to?(:foo) && responds_to?(:bar)
    an_argument.foo + an_argument.bar
  else
    raise "#{an_argument} can't quack properly; is it duck-like?"
  end
end

Installation

Riding the Rails

Add the following to your environment.rb:

config.gem 'gcnovus-quacks_like', :version => '~> 1.0.0', :lib => 'quacks_like', 
 :source => 'http://gems.github.com'

Anywhere else

From your command prompt:

sudo gem install gcnovus-quacks_like

Setting it up

Globally

If you don’t mind mucking with Kernel and want the easiest thing that could possibly work, do this:

require 'rubygems'
require 'gcnovus-quacks_like'
QuacksLike.install_everywhere!

Or just for one class

require 'rubygems'
require 'gcnovus-quacks_like'

class MyClass
  include QuacksLike    # for instance methods
  extend  QuacksLike    # for class methods
end

Defined Under Namespace

Classes: Matcher

Constant Summary collapse

VERSION =
'1.0.1'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.install_everywhere!Object



58
59
60
61
62
# File 'lib/quacks_like.rb', line 58

def self.install_everywhere!
  Kernel.class_eval do
    include ::QuacksLike
  end
end

Instance Method Details

#quacks_like?(*methods) ⇒ Boolean

Create a new matcher that matches all of the methods given.

Raises a NoMethodError if any method does not respond to :to_sym.

Raises a ArgumentError if any method responds to :to_sym but the result is not a Symbol.

Returns:

  • (Boolean)


71
72
73
# File 'lib/quacks_like.rb', line 71

def quacks_like?(*methods)
  ::QuacksLike::Matcher.new(*methods)
end