-
-
Save 2called-chaos/9afa3b5499330c36fa0f to your computer and use it in GitHub Desktop.
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
# That is _NOT_ how you do it. you define it on the class generally (all new instances will have them) instead of just the instance. | |
def accept_virtual *fields | |
fields.each {|f| self.class.__send__(:attr_accessor, f) } | |
end | |
# That is a way but it's dirty :) | |
def accept_virtual *fields | |
metaclass = class << self; self; end | |
fields.each do |f| | |
metaclass.__send__(:define_method, :"#{f}") { instance_variable_get(:"@#{f}") } | |
metaclass.__send__(:define_method, :"#{f}=") {|v| instance_variable_set(:"@#{f}", v) } | |
end | |
end | |
# That's also a thing | |
foo = "bar" | |
foo.bar? # NoMethodError: undefined method `bar?' for "bar":String | |
def foo.bar? | |
self == "bar" | |
end | |
foo.bar? # true | |
foo.replace("baz") | |
foo.bar? # false | |
"".bar? # NoMethodError: undefined method `bar?' for "":String |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment