> For the complete documentation index, see [llms.txt](https://huang-jason.gitbook.io/ruby-rails-syntax/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://huang-jason.gitbook.io/ruby-rails-syntax/module.md).

# module

<http://lizabinante.com/blog/modules-and-self-in-ruby/>

## Module Mixin

### `extend` vs. `include` in classes

* `include`: instance methods
* `extend`: class methods

```ruby
module Animals
  def mammals
    ["sloths", "puppies", "porcupines"]
  end
end

# - - - - - - - - include
class Zoo
  include Animals
end

zoo = Zoo.new
zoo.mammals # => ["sloths", "puppies", "porcupines"]
zoo.methods - Object.methods # => mammals

# - - - - - - - - extend
class PetStore
  extend Animals
end

PetStore.mammals # => ["sloths", "puppies", "porcupines"]
pet_store = PetStore.new
pet_store.mammals # => undefined method `mammals' for #<PetStore:0x007f858a919f30> (NoMethodError)

PetStore.methods - Object.methods # => mammals
pet_store = PetStore.new
pet_store.methods - Object.methods # =>
```

## Module Methods

`extend self`:

* Not change the behavior of include or extend in your classes

`self` method name prefix

* change the behavior of include or extend in your classes (`self` prefix can not be mixed in)
* only access some of methods in module (access `self` prefix only)

#### `extend self`

```ruby
module Animals
  extend self

  def mammals
    ["sloths", "puppies", "porcupines"]
  end

  def sea_creatures
    ["narwhal", "starfish", "dolphin"]
  end
end

Animals.mammals # => ["sloths", "puppies", "porcupines"]
Animals.sea_creatures # => ["narwhal", "starfish", "dolphin"]

# - - - - - - - - include
class Zoo
  include Animals
end

Zoo.mammals # => undefined method `mammals' for Zoo:Class (NoMethodError)
zoo = Zoo.new
zoo.mammals # => ["sloths", "puppies", "porcupines"]

# - - - - - - - - extend
class PetStore
  extend Animals
end

PetStore.mammals # => ["sloths", "puppies", "porcupines"]
pet_store = PetStore.new
pet_store.mammals # => undefined method `mammals' for #<PetStore:0x007f858a919f30> (NoMethodError)
```

#### `self` method name prefix

```ruby
module Animals
  def self.mammals
    ["sloths", "puppies", "porcupines"]
  end

  def sea_creatures
    ["narwhal", "starfish", "dolphin"]
  end
end

Animals.mammals # => ["sloths", "puppies", "porcupines"]
Animals.sea_creatures # => undefined method

# - - - - - - - - include
class Zoo
  include Animals
end

Zoo.mammals # => undefined method
Zoo.sea_creatures # => undefined method
zoo = Zoo.new
zoo.mammals # => undefined method
zoo.sea_creatures # => ["narwhal", "starfish", "dolphin"]

# - - - - - - - - extend
class PetStore
  extend Animals
end

PetStore.mammals # => undefined method
PetStore.sea_creatures # => ["narwhal", "starfish", "dolphin"]

pet_store = PetStore.new
pet_store.mammals # => undefined method
pet_store.sea_creatures # => undefined method
```
