Skip to content

Instantly share code, notes, and snippets.

@nakwa
Last active September 15, 2017 11:46
Show Gist options
  • Save nakwa/f570c6f6ba4280c383658dbe7a5f4d13 to your computer and use it in GitHub Desktop.
Save nakwa/f570c6f6ba4280c383658dbe7a5f4d13 to your computer and use it in GitHub Desktop.
Ruby fun stuff (class inheritance, etc)
class Parent
class << self
attr_accessor :something
def something(value = nil)
@something = value ? value : @something
end
def inherited(subclass)
self.instance_variables.each do |var|
subclass_variable_value = self.instance_variable_get(var).dup
subclass.instance_variable_set(var, subclass_variable_value)
end
end
end
attr_accessor :something
self.something = 'Parent Default'
def something(value = nil)
@something = value ? value : @something ? @something : self.class.something
end
end
class Child < Parent
# inherited form Parent.something
end
class GrandChild < Child
something "GrandChild default"
end
Parent.something
# => "Parent Default"
Parent.something = "Parent something else"
# => "Parent something else"
Parent.something
# => "Parent something else"
parent = Parent.new
# => #<Parent:0x007fc593474900>
parent.something
# => "Parent something else"
parent.something = "yet something different"
# => "yet something different"
parent.something
# => "yet something different"
parent.class.something
# => "Parent something else"
Child.something
# => "Parent Default"
child = Child.new
# => #<Child:0x007fc5934241f8>
child.something
# => "Parent Default"
GrandChild.something
# => "GrandChild default"
GrandChild.something("grandchild something else")
# => "grandchild something else"
GrandChild.something
# => "grandchild something else"
GrandChild.superclass.something
# => "Parent Default"
grandchild = GrandChild.new
# => #<GrandChild:0x007fc5933e70c8>
grandchild.something
# => "grandchild something else"
grandchild.something = "whatever"
# => "whatever"
GrandChild.something
# => "grandchild something else"
grandchild.something
# => "whatever"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment