# Include and Extend

*Published on September 25, 2021*

---


Here’s a neat trick I learned today.

Typically, when a class includes a module, the module methods become instance methods on the including class. However, with just a little metaprogramming, a module can provide both instance and class methods to the including class. Here’s how that works.

```ruby
module Taggable
  def self.included(base)
    puts "Taggable is included in #{base}..extending it now."
    base.extend(ClassMethods)
  end

  def save
    puts "instance method: Saving the post"
  end

  module ClassMethods
    def find(id)
      puts "class method: Finding post with the id #{id}"
    end
  end
end

class Post
  include Taggable

end

# Usage
Post.find(3)
post = Post.new
post.save 

# Output
# Taggable is included in Post..extending it now.
# class method: Finding post with the id 3
# instance method: Saving the post
```

Here,&nbsp;`save`&nbsp;is a regular method in the&nbsp;`Taggable`&nbsp;module that becomes an instance method for&nbsp;`Post`. On the other hand,&nbsp;`find`&nbsp;is a method defined in the&nbsp;`Taggable::ClassMethods`&nbsp;module, that becomes a class method on the&nbsp;`Post`&nbsp;class.

This works because Ruby provides a hook method&nbsp;`Module.included(base)`&nbsp;that is invoked whenever another module or a class includes the module containing the above method.

```ruby
module A
  def A.included(mod)
    puts "#{self} included in #{mod}"
  end
end

module Enumerable
  include A
end

# prints "A included in Enumerable"
```

Now, when&nbsp;`Post`&nbsp;class includes&nbsp;`Taggable`&nbsp;module,&nbsp;`included`&nbsp;is invoked, and the&nbsp;`Post`&nbsp;class is passed as the&nbsp;`base`&nbsp;argument. Then, we extend&nbsp;`Post`&nbsp;with&nbsp;`ClassMethods`, which adds the methods defined in the&nbsp;`ClassMethods`&nbsp;as the class methods on the&nbsp;`Post`&nbsp;class.

```ruby
def self.included(base)
  puts "Taggable is included in #{base}..extending it now."
  base.extend(ClassMethods)
end
```

As a result,&nbsp;`Post`&nbsp;gets both instance methods like&nbsp;`save`&nbsp;and class methods like&nbsp;`find`.

This&nbsp;**include-and-extend**&nbsp;trick gives you a nice way to structure the library. With a single&nbsp;`include`, your class gets access to instance and class methods defined in a well-isolated module. Rails heavily used this pattern, which was later encoded into a feature called concerns, which I will explore in&nbsp;[a future post](/how-rails-concerns-work-and-how-to-use-them).

