Created
April 19, 2021 08:57
-
-
Save vysogot/4c87fe1809968dd726fa8596664b45b8 to your computer and use it in GitHub Desktop.
Simple configurable extension to a class
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
# Animals share some behaviour but each kind needs to be configured properly | |
# I used it to configure sidekiq workers that share sending metrics, logging, | |
# or error handling, but some of them don't send metrics for example | |
# and they need to be configured. | |
class Animal | |
def say_hi | |
puts(greeting_prefix + config.name + hobby_prefix + config.hobby) | |
end | |
private | |
class Config | |
attr_accessor :name, :hobby | |
end | |
class << self | |
attr_accessor :config | |
def configure | |
yield(config) | |
end | |
def config | |
@config ||= Config.new | |
end | |
end | |
def config | |
self.class.config | |
end | |
def hobby_prefix | |
' and I like ' | |
end | |
end | |
class Dog < Animal | |
configure do |c| | |
c.name = 'Scooby' | |
c.hobby = 'diving' | |
end | |
def greeting_prefix | |
'Woof woof, my name is ' | |
end | |
end | |
class Cat < Animal | |
configure do |c| | |
c.name = 'Suzy' | |
c.hobby = 'walking' | |
end | |
def greeting_prefix | |
'Miau miau, my name is ' | |
end | |
end | |
Dog.new.say_hi | |
Cat.new.say_hi | |
# Woof woof, my name is Scooby and I like diving | |
# Miau miau, my name is Suzy and I like walking |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment