Skip to content

Instantly share code, notes, and snippets.

@2called-chaos
Created December 14, 2015 23:02
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 2called-chaos/9afa3b5499330c36fa0f to your computer and use it in GitHub Desktop.
Save 2called-chaos/9afa3b5499330c36fa0f to your computer and use it in GitHub Desktop.
# 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