aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/concern.rb
blob: 2d87e8d0e5e3167b50df09108ebecb26b7a97586 (plain) (blame)
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
62
63
64
# A typical module looks like this
#
#   module M
#     def self.included(base)
#       base.send(:extend, ClassMethods)
#       base.send(:include, InstanceMethods)
#       scope :foo, :conditions => { :created_at => nil }
#     end
#
#     module ClassMethods
#       def cm; puts 'I am a class method'; end
#     end
#
#     module InstanceMethods
#       def im; puts 'I am an instance method'; end
#     end
#   end
#
# By using <tt>ActiveSupport::Concern</tt> the above module could instead be written as:
#
#   module M
#     extend ActiveSupport::Concern
#
#     included do
#       scope :foo, :conditions => { :created_at => nil }
#     end
#
#     module ClassMethods
#       def cm; puts 'I am a class method'; end
#     end
#
#     module InstanceMethods
#       def im; puts 'I am an instance method'; end
#     end
#   end
module ActiveSupport
  module Concern
    def self.extended(base)
      base.instance_variable_set("@_dependencies", [])
    end

    def append_features(base)
      if base.instance_variable_defined?("@_dependencies")
        base.instance_variable_get("@_dependencies") << self
        return false
      else
        return false if base < self
        @_dependencies.each { |dep| base.send(:include, dep) }
        super
        base.extend const_get("ClassMethods") if const_defined?("ClassMethods")
        base.send :include, const_get("InstanceMethods") if const_defined?("InstanceMethods")
        base.class_eval(&@_included_block) if instance_variable_defined?("@_included_block")
      end
    end

    def included(base = nil, &block)
      if base.nil?
        @_included_block = block
      else
        super
      end
    end
  end
end