Sha256: 866799d994b59d65aee03daf3c935096399435445fc892eed9315f070240519f

Contents?: true

Size: 1.23 KB

Versions: 6

Compression:

Stored size: 1.23 KB

Contents

class Class
  # Provides a way to make class attributes that inherit.  Pass
  # in symbols for attribute names.  When the class attribute is accessed from
  # a sublcass, it will be duped.  This allows the children to receive the value
  # from their parent, but then change it only in the child.
  #
  # NOTE: This does not do a deep clone, so multi-nested values may be changed.
  def class_attribute(*attrs)
    attrs.each do |name|
      name = name.to_sym
      ivar = :"@#{name}"

      assigner = :"#{name}="
      define_singleton_method(assigner) do |val|
        instance_variable_set(ivar, val)
      end

      define_singleton_method(name) do
        if instance_variable_defined?(ivar)
          # Get the value from the instance variable
          val = instance_variable_get(ivar)
        else
          # Fetch from parent and dup
          if superclass.respond_to?(name)
            val = superclass.send(name)
          else
            val = nil
          end
          # We need the numeric check because of: https://github.com/opal/opal/issues/1122
          unless val.is_a?(Numeric)
            val = val.dup rescue val
          end

          instance_variable_set(ivar, val)
        end

        val
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
volt-0.9.7.pre8 lib/volt/extra_core/class.rb
volt-0.9.7.pre7 lib/volt/extra_core/class.rb
volt-0.9.7.pre6 lib/volt/extra_core/class.rb
volt-0.9.7.pre5 lib/volt/extra_core/class.rb
volt-0.9.7.pre3 lib/volt/extra_core/class.rb
volt-0.9.7.pre2 lib/volt/extra_core/class.rb