Created
December 19, 2012 04:25
-
-
Save nixpulvis/4334371 to your computer and use it in GitHub Desktop.
What I've come up with playing around trying to dynamically instantiate a class based on input. For example create a Car class if the name of the vehicle is a car's name.
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
module Vehicle | |
@@catigories = { | |
car: ["Focus", "Dart", "Civic"], | |
truck: ["F150", "Super Duty"], | |
van: ["Caravan", "Town and Country"], | |
} | |
def self.category(name) | |
@@catigories.each do |k,v| | |
return k.capitalize if v.include? name | |
end | |
nil # return nill if we didn't find it | |
end | |
def self.new(name) | |
if const_defined? category(name) | |
klass = const_get category(name) | |
else | |
klass = const_set category(name), Class.new | |
end | |
klass.send(:include, self) | |
klass.new name | |
end | |
attr_reader :name | |
def initialize(name) | |
@name = name | |
end | |
def jump_start! | |
puts "Damn it, can't jump #{name}" | |
end | |
end | |
class Car | |
def boost(amount) | |
puts "Zip Zap Zoom, #{name} boosts to level #{amount}" | |
end | |
end | |
car = Vehicle.new "Focus" | |
truck = Vehicle.new "F150" | |
van = Vehicle.new "Caravan" | |
car.jump_start! # will work | |
truck.jump_start! # will work | |
car.boost(1337) # will work | |
truck.boost(31) # will error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment