5

Suppose I have the following namespace with a Base module that defines some methods that can be reused

module MyNameSpace
  module Magic
    extend ActiveSupport::Concern

    class_methods do 
      def magic_field(field_name)
        # Defines methods and attributes based on field name
      end
    end
  end
end

What is the difference (if there is any) between

module MyNameSpace
  module Foo
    extend ActiveSupport::Concern
    include Magic

    included do
      magic_field(:foo)
    end
  end
end

and

module MyNameSpace
  module Foo
    extend ActiveSupport::Concern

    included do
      include Magic
      magic_field(:foo)
    end
  end
end

(The question is about the difference of include Magic being either outside or inside the included block)

Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164

1 Answers1

3

When the concern is included in a class, the include and class_methods allows for the receiving class to inherit those methods.

included adds instance methods while class_methods adds class methods.

Source: Rails Concerns Docs

On the other hand, if your question is the difference between the placement of include Magic, there is no difference in how the class would function.

Wes Foster
  • 8,770
  • 5
  • 42
  • 62
  • Yes my question was about the `ìnclude Magic`either outside or inside the `included` block – Cyril Duchon-Doris Mar 14 '17 at 17:10
  • _When you define more than one included block, it raises an exception_. When using `load` in the rails console, it won't override methods added via the same _Concern_ `included` block, due to [this error](https://stackoverflow.com/a/52459894/4352306): _Cannot define multiple 'included' blocks for a Concern_. So we may say there's an actual difference, because in a _**hot swap**_ `included` block won't be redefined. – rellampec Dec 13 '22 at 19:09