Module: AppleCore::Extensions::Class::ClassMethods

Defined in:
lib/apple_core/extensions/class.rb

Instance Method Summary collapse

Instance Method Details

#class_attribute(method_name, options = {}) ⇒ Object



15
16
17
18
19
20
21
22
23
24
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
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/apple_core/extensions/class.rb', line 15

def class_attribute(method_name, options = {})
  instance_reader = options.fetch(:instance_accessor, true) &&
                    options.fetch(:instance_reader,   true)
  instance_writer = options.fetch(:instance_accessor, true) &&
                    options.fetch(:instance_writer,   true)

  remove_possible_singleton_method(method_name)
  define_singleton_method(method_name) { options[:default] }

  ivar = "@#{method_name}"

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

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

  if instance_reader
    remove_possible_method method_name
    define_method(method_name) do
      if instance_variable_defined?(ivar)
        instance_variable_get ivar
      else
        self.class.public_send method_name
      end
    end
  end

  if instance_writer
    remove_possible_method "#{method_name}="
    attr_writer method_name
  end
end