Created
April 14, 2014 17:59
-
-
Save jbasinger/10669732 to your computer and use it in GitHub Desktop.
Component delegation experiment
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
class Component | |
attr_accessor :property, :another_property | |
end | |
class Entity | |
def initialize() | |
@components = {}; | |
end | |
def add_component(name, comp) | |
raise "Component already exists." unless @components[name].nil? | |
@components[name] = comp | |
@components[name].public_methods(false).each do |method| | |
str = %Q{ | |
def #{method}(*args, &block) | |
@components["#{name}"].__send__(:#{method}, *args, &block) | |
end | |
} | |
instance_eval(str, __FILE__, __LINE__) | |
end | |
end | |
def remove_component(name) | |
return if @components[name].nil? | |
str = %Q{ | |
class << self | |
#{@components[name].public_methods(false).map{|x| "remove_method :#{x}"}.join(";")} | |
end | |
} | |
instance_eval(str, __FILE__, __LINE__) | |
removed_component = @components[name] | |
@components[name] = nil | |
return removed_component | |
end | |
end | |
entity = Entity.new() | |
p "Entity methods init: #{entity.public_methods(false)}" | |
comp = Component.new() | |
p "Component methods: #{comp.public_methods(false)}" | |
entity.add_component("comp", comp); | |
p "Entity methods post: #{entity.public_methods(false)}" | |
entity.property = "test" | |
p "Entity property value: #{entity.property}" | |
entity.remove_component("comp") | |
p "Entity methods after removing comp: #{entity.public_methods(false)}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment