Sha256: 56c101e8cec9d33026ac8cf8123a203b7d12ca8e7b0f7f22c4231963f161a93f

Contents?: true

Size: 1.5 KB

Versions: 22

Compression:

Stored size: 1.5 KB

Contents

#          Copyright (c) 2008 Michael Fellinger m.fellinger@gmail.com
# All files in this distribution are subject to the terms of the Ruby license.

Traits = Hash.new{|h,k| h[k] = {}} unless defined?(Traits)

# Extensions for Object

class Object

  # Adds a method to Object to annotate your objects with certain traits.
  # It's basically a simple Hash that takes the current object as key
  #
  # Example:
  #
  #   class Foo
  #     trait :instance => false
  #
  #     def initialize
  #       trait :instance => true
  #     end
  #   end
  #
  #   Foo.trait[:instance]
  #   # false
  #
  #   foo = Foo.new
  #   foo.trait[:instance]
  #   # true

  def trait hash = nil
    if hash
      Traits[self].merge! hash
    else
      Traits[self]
    end
  end

  # builds a trait from all the ancestors, closer ancestors
  # overwrite distant ancestors
  #
  # class Foo
  #   trait :one => :eins
  #   trait :first => :erstes
  # end
  #
  # class Bar < Foo
  #   trait :two => :zwei
  # end
  #
  # class Foobar < Bar
  #   trait :three => :drei
  #   trait :first => :overwritten
  # end
  #
  # Foobar.ancestral_trait
  # {:three=>:drei, :two=>:zwei, :one=>:eins, :first=>:overwritten}

  def ancestral_trait
    if respond_to?(:ancestors)
      ancs = ancestors
    else
      ancs = self.class.ancestors
    end
    ancs.reverse.inject({}){|s,v| s.merge(v.trait)}.merge(trait)
  end

  # trait for self.class

  def class_trait
    if respond_to?(:ancestors)
      trait
    else
      self.class.trait
    end
  end
end

Version data entries

22 entries across 22 versions & 5 rubygems

Version Path
Pistos-ramaze-2008.09 lib/ramaze/snippets/object/traits.rb
Pistos-ramaze-2008.12 lib/ramaze/snippets/object/traits.rb
Pistos-ramaze-2009.01 lib/ramaze/snippets/object/traits.rb
Pistos-ramaze-2009.02 lib/ramaze/snippets/object/traits.rb
clivecrous-ramaze-0.3.9.5 lib/ramaze/snippets/object/traits.rb
manveru-ramaze-2008.07 lib/ramaze/snippets/object/traits.rb
manveru-ramaze-2008.08 lib/ramaze/snippets/object/traits.rb
manveru-ramaze-2008.09 lib/ramaze/snippets/object/traits.rb
manveru-ramaze-2008.10 lib/ramaze/snippets/object/traits.rb
manveru-ramaze-2008.12 lib/ramaze/snippets/object/traits.rb
manveru-ramaze-2009.01 lib/ramaze/snippets/object/traits.rb
ptomato-ramaze-2009.02.1 lib/ramaze/snippets/object/traits.rb
ptomato-ramaze-2009.02 lib/ramaze/snippets/object/traits.rb
ramaze-0.3.0 lib/ramaze/snippets/object/traits.rb
ramaze-0.3.5 lib/ramaze/snippets/object/traits.rb
ramaze-2008.06 lib/ramaze/snippets/object/traits.rb
ramaze-2009.01 lib/ramaze/snippets/object/traits.rb
ramaze-0.3.9.1 lib/ramaze/snippets/object/traits.rb
ramaze-2008.11 lib/ramaze/snippets/object/traits.rb
ramaze-0.3.9 lib/ramaze/snippets/object/traits.rb