Traits for Ruby 2, as described in Traits: A Mechanism for Fine-grained Reuse by Ducasse, Nierstrasz, Schärli, Wuyts and Black.
A class becomes a trait when it extends Fabrik::Trait.
class Tiger
extend Fabrik::Trait
endTraits provide methods within a provides block.
class Panthera
extend Fabrik::Trait
provides do
def roar; :roar! end
end
endclass Tiger
extend Fabrik::Trait
provides do
def mother; :tigress end
def father; :tiger end
end
endclass Lion
extend Fabrik::Trait
provides do
def mother; :lioness end
def father; :lion end
end
endAlternatively, a trait can be created with Fabrik::Trait.build.
Lion = Fabrik::Trait.build do
def mother; :lioness end
def father; :lion end
endA class uses traits by extending Fabrik::Composer and composing the traits.
class Tigon
extend Fabrik::Composer
compose Panthera, Tiger, Lion
endtigon = Tigon.new
tigon.roar # => :roar!
tigon.mother # => raises ConflictingMethods errorConflicting 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]
endtigon = Tigon.new
tigon.roar # => :roar!
tigon.mother # => :lioness
tigon.father # => :tigerTraits can be composed from other traits in the same way:
class TigonTrait
extend Fabrik::Trait
compose Panthera,
Tiger[exclude: :mother],
Lion[exclude: :father]
endOr by using .build:
TigonTrait = Fabrik::Trait.build(Panthera, Tiger[exclude: :mother], Lion[exclude: :father]) do
def scratch; :scratched end
endView the specs for further examples, including composable traits and traits that provide methods from shared modules.
Built by Joe Corcoran.
MIT.