Last active
April 8, 2024 00:11
-
-
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
This file contains 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 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