Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Last active August 29, 2015 14:02
Show Gist options
  • Save JoshCheek/0d3f12d6300d2e3b8ec9 to your computer and use it in GitHub Desktop.
Save JoshCheek/0d3f12d6300d2e3b8ec9 to your computer and use it in GitHub Desktop.
Object model results
# Classes are containers for methods
# Objects are containers for instance variables
# scopes are containers for local variables
# and execute in the context of an object
# When you call a method on an object
# it looks it up in the class
# if it doesn't find it there
# it continues looking it up in the chain of superclasses
# Module is a container for methods
# When you include it into a class
# It makes a new class with the module's methods
# and sticks that into the inheritance hierarchy
# When you define a method on an object
# It makes a new class called the singleton class
# and defines the method there
# and puts that into the inheritance hierarchy
class Address
def initialize(line1, line2)
@line1 = line1
@line2 = line2
end
def line1
@line1
end
def line2
@line2
end
end
class User
def initialize(name)
@name = name
end
def name=(new_name)
@name = new_name
end
def name
@name
end
end
module HasAddress
def address=(new_address)
@address = new_address
end
def address
@address
end
end
class UserWithAddress < User
include HasAddress
def initialize(name, address)
@address = address
super(name)
end
end
class User
def self.default
new("John Doe")
end
end
address = Address.new '1801 S. Bell St', 'Arlington, VA 22020'
user = UserWithAddress.new 'Josh', address
user.address.line1 # => "1801 S. Bell St"
User.default.name # => "John Doe"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment