Include_vs_extend

include
include use for adding methods to an instance of a class.

example

example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
module Foo
  def foo
    p 'Hi foo'
  end
end

class Bar
  include Foo
end

bar = Bar.new
bar.foo # => Hi foo

Bar.foo # => NoMethodError: undefined method ‘foo’ for Bar:Class

extend
extend use for adding class methods.

example

example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
module Foo
  def foo
    p 'Hi foo'
  end
end

class Baz
  extend Foo
end

Bar.foo # => Hi foo

bar = Bar.new
bar.foo # => NoMethodError: undefined method ‘foo’ for #<Baz:0x1e708>

Using include to append both class and instance methods
You will see in Ruby is to use include to append both class and instance methods.
The reason for this is that include has a self.included hook you can use to modify the class that is including a module.

example

example
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
module Foo
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def bar
      p 'class method'
    end
  end

  def foo
    p 'instance method'
  end
end

class Bar
  include Foo
end

Bar.bar # => class method
Bar.foo # => NoMethodError: undefined method ‘foo’ for Baz:Class

Bar.new.foo # => instance method
Bar.new.bar # => NoMethodError: undefined method ‘bar’ for #<Baz:0x1e3d4>