Modules Advanced in Ruby
Advanced mixin patterns, hooks, lookup order, and refinements.
include vs extend vs prepend
include adds instance methods; extend adds class methods; prepend inserts before the class in lookup (allowing method interception).
module Taggable
def tag; :tagged end
end
class Post
include Taggable
end
class Registry
extend Taggable
end
Post.new.tag # instance method
Registry.tag # class method
module Loud
def to_s; "LOUD:" + super end
end
class Name; def to_s = "name" end
class Name
prepend Loud
end
Name.new.to_s # => "LOUD:name"
Hooks
React to mixins with callbacks. Common hooks: included, extended, prepended, inherited, method_added.
module M
def self.included(base); base.extend(ClassMethods) end
module ClassMethods; def m!; :ok end end
end
class C; include M end
C.m!
Refinements
Scope monkey patches to specific files/contexts.
module Shout
refine String do
def shout; upcase + "!" end
end
end
using Shout
"hi".shout # => "HI!"
Visibility tweaks inside modules
You can mark selected methods as private when mixed in.
module Helpers
def helper; :h end
private :helper
end
Constant autoload
Defer constant loading until first use to reduce boot time.
module MyLib
autoload :Parser, "my_lib/parser"
end
Summary
- Choose
include/extend/prependintentionally;prependenables interception - Use hooks to attach class‑level APIs; refinements to limit monkey patches
autoloadcan improve load time by lazy‑loading constants