Skip to content

Instantly share code, notes, and snippets.

@vysogot
Created April 19, 2021 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vysogot/4c87fe1809968dd726fa8596664b45b8 to your computer and use it in GitHub Desktop.
Save vysogot/4c87fe1809968dd726fa8596664b45b8 to your computer and use it in GitHub Desktop.
Simple configurable extension to a class
# 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