1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00
Files
til/ruby/create-a-module-of-utility-functions.md

1.6 KiB

Create A Module Of Utility Functions

In my latest blog post, I went into full detail about how the Module#module_function method works. It creates both a module of utility functions that we can access directly on that module like we would with self methods. It can also be included in a class as a way of sharing copies of those utility functions with the class. A key point to them being copies is that they can then be overridden by the including class.

Here is the example I used in the blog post:

module MarkdownHelpers
  module_function

  def heading(text, level = 1)
    ("#" * level) + " #{text}"
  end

  def link(text, href)
    "[#{text}](#{href})"
  end

  def image(alt_text, href)
    "!#{link(alt_text, href)}"
  end
end

I won't cover everything that the blog post covers, but what I found really nice about this pattern is that I can call those utility functions directly with the module as the receiver:

$ ruby -r ./markdown_helpers.rb -e 'puts MarkdownHelpers.link("Click here", "https://example.com")'
[Click here](https://example.com)

The alternative to this generally looks like:

module MarkdownHelpers
  def self.heading(text, level = 1)
    ("#" * level) + " #{text}"
  end

  def self.link(text, href)
    "[#{text}](#{href})"
  end

  def self.image(alt_text, href)
    "!#{link(alt_text, href)}"
  end
end

That would be fine, but we completely lose out on the ability to include it as a mix-in with other classes.