mlangenberg (owner)

Revisions

gist: 7760 Download_button fork
public
Public Clone URL: git://gist.github.com/7760.git
Embed All Files: show embed
namespaced_class_inheritable_accessor.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
module Extlib
  def self.class_inheritable_reader(klass, *ivars)
    instance_reader = ivars.pop[:reader] if ivars.last.is_a?(Hash)
    
    ivars.each do |ivar|
      klass.class_eval <<-RUBY, __FILE__, __LINE__ + 1
def self.#{ivar}
return @#{ivar} if self == #{klass} || defined?(@#{ivar})
ivar = superclass.#{ivar}
return nil if ivar.nil? && !#{klass}.instance_variable_defined?("@#{ivar}")
@#{ivar} = ivar && !ivar.is_a?(Module) && !ivar.is_a?(Numeric) ? ivar.dup : ivar
end
RUBY
      unless instance_reader == false
        klass.class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{ivar}
self.class.#{ivar}
end
RUBY
      end
    end
  end
  
  def self.class_inheritable_writer(klass, *ivars)
    instance_writer = ivars.pop[:instance_writer] if ivars.last.is_a?(Hash)
    ivars.each do |ivar|
      klass.class_eval <<-RUBY, __FILE__, __LINE__ + 1
def self.#{ivar}=(obj)
@#{ivar} = obj
end
RUBY
      unless instance_writer == false
        klass.class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{ivar}=(obj) self.class.#{ivar} = obj end
RUBY
      end
    end
  end
  
  def self.class_inheritable_accessor(klass, *syms)
    class_inheritable_reader(klass, *syms)
    class_inheritable_writer(klass, *syms)
  end
end
 
module Merb; end
 
class Merb::Controller
  Extlib::class_inheritable_accessor self, :_form_class
end
 
class Merb::Mailer
  Extlib::class_inheritable_accessor self, :config
 
  def initialize
    self.config = 'hello' if config.nil?
  end
end
 
puts Merb::Mailer.new.config #=> 'hello'