Sha256: 3b2372ffdf883497b65960795e856f9f8f59f53dd4d7bb1614c5de7e39d0786a

Contents?: true

Size: 1.74 KB

Versions: 2

Compression:

Stored size: 1.74 KB

Contents

module Attributes
  VERSION = '3.3.0'
  def self.version() VERSION end

  def attributes *a, &b
    unless a.empty?
      hashes, names = a.partition{|x| Hash === x}

      names_and_defaults = {}
      hashes.each{|h| names_and_defaults.update h}
      names.flatten.compact.each{|name| names_and_defaults.update name => nil}

      names_and_defaults.each do |name, default|
        init = b || lambda { default }
        ivar, getter, setter, query = "@#{ name }", "#{ name }", "#{ name }=", "#{ name }?"

        define_method(setter) do |value|
          instance_variable_set ivar, value
        end

        define_method(getter) do |*value|
          unless value.empty?
            send setter, value.shift
          else
            defined = instance_eval "defined? #{ ivar }"
            send setter, instance_eval(&init) unless defined
            instance_variable_get ivar
          end
        end

        alias_method query, getter

        (attributes << name).uniq!
        attributes
      end
    else
      begin
        __attribute_list__
      rescue NameError
        singleton_class =
          class << self
            self
          end
        singleton_class.module_eval <<-code
          attribute_list = []
          define_method('attribute_list'){ attribute_list }
          alias_method '__attribute_list__', 'attribute_list'
        code
        __attribute_list__
      end
    end
  end

  %w( __attributes__ __attribute__ attribute ).each{|dst| alias_method dst, 'attributes'}
end

class Object
  def attributes *a, &b
    sc = 
      class << self
        self
      end
    sc.attributes *a, &b
  end
  %w( __attributes__ __attribute__ attribute ).each{|dst| alias_method dst, 'attributes'}
end

class Module; include Attributes; end

Version data entries

2 entries across 1 versions & 1 rubygems

Version Path
attributes-3.3.0 lib/attributes-3.3.0.rb
attributes-3.3.0 lib/attributes.rb