Sha256: 61aefde613a7a7f75659a711f090d85a01eb89ee4bd44a3b9f42da04cf846f0f

Contents?: true

Size: 1.16 KB

Versions: 7

Compression:

Stored size: 1.16 KB

Contents

module Yaks
  class Attributes < Module
    attr_reader :defaults, :attributes

    def initialize(*attrs)
      @defaults   = attrs.last.instance_of?(Hash) ? attrs.pop : {}
      @attributes = attrs + @defaults.keys
    end

    def add(*attrs)
      defaults = attrs.last.instance_of?(Hash) ? attrs.pop : {}
      self.class.new(*[*(attributes+attrs), @defaults.merge(defaults)])
    end

    def included(descendant)
      descendant.module_exec(self) do |this|
        include InstanceMethods,
                Anima.new(*this.attributes),
                Anima::Update

        this.attributes.each do |attr|
          define_method attr do |value = Undefined|
            if value.equal? Undefined
              instance_variable_get("@#{attr}")
            else
              update(attr => value)
            end
          end
        end

        define_singleton_method(:attributes) { this }
      end
    end

    module InstanceMethods
      def initialize(attributes = {})
        super(self.class.attributes.defaults.merge(attributes))
      end

      def append_to(type, *objects)
        update(type => instance_variable_get("@#{type}") + objects)
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
yaks-0.7.3 lib/yaks/attributes.rb
yaks-0.7.2 lib/yaks/attributes.rb
yaks-0.7.1 lib/yaks/attributes.rb
yaks-0.7.0 lib/yaks/attributes.rb
yaks-0.6.2 lib/yaks/attributes.rb
yaks-0.6.1 lib/yaks/attributes.rb
yaks-0.6.0 lib/yaks/attributes.rb