Class: Object

Inherits:
BasicObject
Defined in:
lib/concern.rb

Class Method Summary collapse

Class Method Details

.concern(lib, options = {}) ⇒ Object



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
# File 'lib/concern.rb', line 12

def self.concern(lib, options={})
  # load delegate
  lib = lib.to_s
  klass = Concern.classify(lib)
  begin
    klass = eval(klass)
  rescue
    require lib
    klass = eval(klass)
  end

  unless klass.instance_methods.map{|x|x.to_s}.include?('concerned=')
    raise "A concern must always extend Concern"
  end

  # make accessor
  accessor = lib.split('/').last.to_sym
  eval <<-EOF
    def #{accessor}
      return @#{accessor} if @#{accessor}
      @#{accessor} = #{klass}.new
      @#{accessor}.concerned = self
      @#{accessor}
    end
  EOF

  # call included
  base = eval(name) #self.class is always Class, but name is class that called concern
  klass.included(base) if klass.respond_to? :included

  # delegate methods
  if options[:delegate]
    methods = if options[:delegate].is_a?(Array)
      options[:delegate]
    else
      klass.public_instance_methods(false)
    end

    methods.each do |method|
      eval <<-EOF
        def #{method}(*args)
          #{accessor}.#{method}(*args)
        end
      EOF
    end
  end
end