Created
June 21, 2015 03:06
-
-
Save ryunp/99bb85f56244a959da2a 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
# Ryan Paul, 6/20/15, Sandboxing with ruby | |
# See bottom for output | |
# More advanced example on class surfing: | |
# http://daniel.fone.net.nz/blog/2013/05/27/generating-a-class-hierarchy-in-ruby/ | |
# Interesting discussion on static vs dynamic languages and Modules: | |
# http://ducktypo.blogspot.com/2010/08/why-inheritance-sucks.html | |
# C style main block (just cause like, why not) | |
def main | |
# ctor: name | |
a = Item.new("Parent") | |
a.object_info | |
# ctor: name, desc | |
b = SubItem.new("Child", "cool!") | |
b.object_info | |
# ctor: name, desc, num | |
c = SubSubItem.new("SubChild", "way cooler!", 69) | |
c.object_info | |
end | |
# Methods we want all classes to have access to | |
module Utility | |
def gen_class_tree obj | |
klass = obj.class | |
tree = [klass] | |
tree << klass while klass = klass.superclass | |
tree.reverse.join('::') | |
end | |
def object_info | |
#print "----\n" | |
print "#{gen_class_tree self}\n" # List class hierarchy | |
print "#{self.instance_variables}\n" # List variables | |
print "[#{self}]\n" # Calls to_s without adding quotes | |
print "----\n" # Seperator | |
end | |
end | |
# Base class that has cool custom utility functionality | |
class Item | |
include Utility | |
def initialize name | |
@name = name | |
end | |
def to_s | |
"{name: '#{@name}'}" | |
end | |
end | |
# Sub class | |
class SubItem < Item | |
def initialize name, desc | |
super name | |
@desc = desc | |
end | |
def to_s | |
super + ", {desc: '#{@desc}'}" | |
end | |
end | |
# Sub class of sub class | |
class SubSubItem < SubItem | |
def initialize name, desc, num | |
super name, desc | |
@num = num | |
end | |
def to_s | |
super + ", {num: #{@num}}" | |
end | |
end | |
# Run main block after classes defined | |
main() | |
# OUTPUT: | |
# | |
# BasicObject::Object::Item | |
# [:@name] | |
# [{name: 'Parent'}] | |
# ---- | |
# BasicObject::Object::Item::SubItem | |
# [:@name, :@desc] | |
# [{name: 'Child'}, {desc: 'cool!'}] | |
# ---- | |
# BasicObject::Object::Item::SubItem::SubSubItem | |
# [:@name, :@desc, :@num] | |
# [{name: 'SubChild'}, {desc: 'way cooler!'}, {num: 69}] | |
# ---- | |
# [Finished in 0.0s] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment