Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active April 8, 2024 00:11
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 havenwood/f44719666718be15f0a146dfef5441d5 to your computer and use it in GitHub Desktop.
Save havenwood/f44719666718be15f0a146dfef5441d5 to your computer and use it in GitHub Desktop.
My example showing dynamic top level instance variables with attrs for #ruby IRC
class Attributes < Module
def initialize(**attributes)
self.class.class_eval do
define_method :included do |klass|
klass.class_eval do
attributes.each do |key, value|
instance_variable_set "@#{key}", value
singleton_class.class_eval { attr_accessor key }
end
end
end
end
end
end
module Universe
include Attributes.new(meaning: 42, size: nil)
end
pp Universe.meaning
#>> 42
Universe.size = Float::INFINITY
pp Universe.size
#>> Infinity
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment