Created
May 3, 2026 15:33
-
-
Save havenwood/f42001c1dec9a0382c38504ae6cc16cf to your computer and use it in GitHub Desktop.
An example showing a class inheriting from Module for custom exceptions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Alert < Module | |
| COLORS = {red: 31, yellow: 33, blue: 34, magenta: 35, cyan: 36} | |
| def initialize(message: nil, color: :red) | |
| super() | |
| @message = message | |
| @color = COLORS.fetch(color) | |
| end | |
| def included(base) | |
| message= @message | |
| color = @color | |
| base.define_method(:initialize) { |msg = message| super(msg) } | |
| base.define_method(:full_message) do |**opts| | |
| "\e[#{color}m#{super(**opts)}\e[0m" | |
| end | |
| end | |
| end | |
| class LowBattery < StandardError | |
| include Alert.new(message: 'battery low', color: :yellow) | |
| end | |
| raise LowBattery |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment