Skip to content

Instantly share code, notes, and snippets.

@bmarini
Created December 29, 2010 23:21
Show Gist options
  • Save bmarini/759204 to your computer and use it in GitHub Desktop.
Save bmarini/759204 to your computer and use it in GitHub Desktop.
Rails 3 inspired modularity
# Making a large class modular
# * Put core functionality into Base module inside your class
# * Split other functionality into modules and include them at the bottom of the
# your class
# * Now it is easy to reuse or recreate custom versions of the class by creating
# new classes, including only some modules, swapping modules out for others, etc.
class MainClass
module Base
attr_accessor :name
def initialize(name)
@name = name
end
end
module Upcase
def initialize(first)
super
@name.upcase!
end
end
module Title
def initialize(name)
super
@name = "Mr. #{@name}"
end
end
include Base
include Upcase
include Title
end
# This is the cool part. You can use the parts of this class like legos to
# create your own customized version
class MyCustomClassWithJustBase
include MainClass::Base
end
class MyCustomClassWithNoUpcase
include MainClass::Base
include MainClass::Title
end
class MyCustomClassWithUpcaseLast
include MainClass::Base
include MainClass::Title
include MainClass::Upcase
end
# Examples
puts MainClass.new("anderson").name # => Mr. ANDERSON
puts MyCustomClassWithJustBase.new("anderson").name # => anderson
puts MyCustomClassWithNoUpcase.new("anderson").name # => Mr. anderson
puts MyCustomClassWithUpcaseLast.new("anderson").name # => MR. ANDERSON
# Ancestry
p MyCustomClassWithJustBase.ancestors
# => [MyCustomClassWithJustBase, MainClass::Base, Object, Kernel]
p MyCustomClassWithNoUpcase.ancestors
# => [MyCustomClassWithNoUpcase, MainClass::Title, MainClass::Base, Object, Kernel]
p MyCustomClassWithJustBase.ancestors
# => [MyCustomClassWithJustBase, MainClass::Base, Object, Kernel]
p MainClass.ancestors
# => [MainClass, MainClass::Title, MainClass::Upcase, MainClass::Base, Object, Kernel]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment