Method: Injectable::ClassMethods#simple_class_attribute

Defined in:
lib/injectable/class_methods.rb

#simple_class_attribute(*attrs) ⇒ Object

Blatantly stolen from rails’ ActiveSupport. This is a simplified version of class_attribute



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/injectable/class_methods.rb', line 25

def simple_class_attribute(*attrs)
  attrs.each do |name|
    define_singleton_method(name) { nil }

    ivar = "@#{name}"

    define_singleton_method("#{name}=") do |val|
      singleton_class.class_eval do
        define_method(name) { val }
      end

      if singleton_class?
        class_eval do
          define_method(name) do
            if instance_variable_defined? ivar
              instance_variable_get ivar
            else
              singleton_class.send name
            end
          end
        end
      end
      val
    end
  end
end