Sha256: 24b9c30a61692620368b30fb71dda14a4146768a15bf7d016e8db523217dc7cf

Contents?: true

Size: 1.24 KB

Versions: 1

Compression:

Stored size: 1.24 KB

Contents

# encoding: utf-8

module Assertion

  module DSL

    # Allows adding aliases to values of the `#attributes` hash.
    #
    module Attributes

      # List of declared attributes
      #
      # @return [Array<Symbol>]
      #
      def attributes
        @attributes ||= []
      end

      # Declares new attribute(s) by name(s)
      #
      # @param [#to_sym, Array<#to_sym>] names
      #
      # @return [undefined]
      #
      # @raise [NameError]
      #   When a given name is either used by instance methods,
      #   or reserved by the `#check` method to be implemented later.
      #
      def attribute(*names)
        names.flatten.map(&:to_sym).each(&method(:__add_attribute__))
      end

      # @private
      def self.extended(klass)
        klass.__send__(:define_method, :attributes) { @attributes ||= {} }
      end

      private

      def __add_attribute__(name)
        __check_attribute__(name)
        define_method(name) { attributes[name] }
        attributes << name.to_sym
      end

      def __check_attribute__(name)
        return unless (instance_methods << :check).include? name
        fail NameError.new "#{self}##{name} is already defined"
      end

    end # module Attributes

  end # module DSL

end # module Assertion

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
assertion-0.2.3 lib/assertion/dsl/attributes.rb