Traits for Ruby 2
Ruby
Latest commit c94d4ac Aug 10, 2016 @joecorcoran committed on GitHub Add email
Permalink
Failed to load latest commit information.
lib
spec
.travis.yml
CODE_OF_CONDUCT.md Add email Aug 10, 2016
Gemfile
LICENSE.txt
README.md
fabrik.gemspec

README.md

Fabrik

Build Status

Traits for Ruby 2, as described in Traits: A Mechanism for Fine-grained Reuse by Ducasse, Nierstrasz, Schärli, Wuyts and Black.

Usage

A class becomes a trait when it extends Fabrik::Trait.

class Tiger
  extend Fabrik::Trait
end

Traits provide methods within a provides block.

class Panthera
  extend Fabrik::Trait

  provides do
    def roar; :roar! end
  end
end
class Tiger
  extend Fabrik::Trait

  provides do
    def mother; :tigress end
    def father; :tiger end
  end
end
class Lion
  extend Fabrik::Trait

  provides do
    def mother; :lioness end
    def father; :lion end
  end
end

Alternatively, a trait can be created with Fabrik::Trait.build.

Lion = Fabrik::Trait.build do
  def mother; :lioness end
  def father; :lion end
end

A class uses traits by extending Fabrik::Composer and composing the traits.

class Tigon
  extend Fabrik::Composer
  compose Panthera, Tiger, Lion
end
tigon = Tigon.new
tigon.roar    # => :roar!
tigon.mother  # => raises ConflictingMethods error

Conflicting methods must be resolved, by exclusion or aliasing during composition, or by overriding in the composing class.

class Tigon
  extend Fabrik::Composer
  compose Panthera,
          Tiger[exclude: :mother],
          Lion[exclude: :father]
end
tigon = Tigon.new
tigon.roar    # => :roar!
tigon.mother  # => :lioness
tigon.father  # => :tiger

Traits can be composed from other traits in the same way:

class TigonTrait
  extend Fabrik::Trait
  compose Panthera,
          Tiger[exclude: :mother],
          Lion[exclude: :father]
end

Or by using .build:

TigonTrait = Fabrik::Trait.build(Panthera, Tiger[exclude: :mother], Lion[exclude: :father]) do
  def scratch; :scratched end
end

View the specs for further examples, including composable traits and traits that provide methods from shared modules.

Credits

Built by Joe Corcoran.

License

MIT.