Skip to content

Instantly share code, notes, and snippets.

@vnegrisolo
Last active September 3, 2016 14:52
Show Gist options
  • Save vnegrisolo/df7f84871711f4a774c1 to your computer and use it in GitHub Desktop.
Save vnegrisolo/df7f84871711f4a774c1 to your computer and use it in GitHub Desktop.
Test how Ruby inheritance works and Modules
module ModuleToBeIncludedByParentClass
def parent; puts 'from included module by parent'; super if defined?(super); end
end
module ModuleToBeExtendedByParentClass
def parent; puts 'from extended module by parent'; super if defined?(super); end
end
module ModuleToBeIncludedByChildClass
def child; puts 'from included module by child'; super if defined?(super); end
end
module ModuleToBeExtendedByChildClass
def child; puts 'from extended module by child'; super if defined?(super); end
end
class ParentClass
include ModuleToBeIncludedByParentClass
extend ModuleToBeExtendedByParentClass
def self.parent; puts 'from parent class self.parent method'; super if defined?(super); end
def self.child; puts 'from parent class self.child method'; super if defined?(super); end
def parent; puts 'from parent class parent method'; super if defined?(super); end
def child; puts 'from parent class child method'; super if defined?(super); end
end
class ChildClass < ParentClass
include ModuleToBeIncludedByChildClass
extend ModuleToBeExtendedByChildClass
def self.parent; puts 'from child class self.parent method'; super if defined?(super); end
def self.child; puts 'from child class self.child method'; super if defined?(super); end
def parent; puts 'from child class parent method'; super if defined?(super); end
def child; puts 'from child class child method'; super if defined?(super); end
end
puts '### class methods'
ParentClass.parent
puts ''
ChildClass.parent
puts ''
ChildClass.child
puts ''
puts '### instance methods'
ParentClass.new.parent
puts ''
ChildClass.new.parent
puts ''
ChildClass.new.child
#=> ### class methods
#=> from parent class self.parent method
#=> from extended module by parent
#=>
#=> from child class self.parent method
#=> from parent class self.parent method
#=> from extended module by parent
#=>
#=> from child class self.child method
#=> from extended module by child
#=> from parent class self.child method
#=>
#=> ### instance methods
#=> from parent class parent method
#=> from included module by parent
#=>
#=> from child class parent method
#=> from parent class parent method
#=> from included module by parent
#=>
#=> from child class child method
#=> from included module by child
#=> from parent class child method
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment