Skip to content

Instantly share code, notes, and snippets.

@3limin4t0r
Created January 10, 2020 10:17
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 3limin4t0r/94f9e96600fceca4e74a9d6f9a2d0f00 to your computer and use it in GitHub Desktop.
Save 3limin4t0r/94f9e96600fceca4e74a9d6f9a2d0f00 to your computer and use it in GitHub Desktop.
# https://ruby-doc.org/stdlib-2.7.0/libdoc/ostruct/rdoc/OpenStruct.html
require 'ostruct'
module Configurable
def config(&block)
@config ||= OpenStruct.new
return @config unless block_given?
@config.tap(&block)
end
end
module Foo
extend Configurable
# setting defaults
config.some_value = 'default value'
config.another = 'default value'
class << self
def some_method
puts "do something with #{config.some_value}"
end
end
end
Foo.some_method
# prints: do something with default value
# in some initializer
Foo.config do |config|
config.some_value = 'configured value'
end
Foo.some_method
# prints: do something with configured value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment