Skip to content
Browse files

Use method-missing

  • Loading branch information...
1 parent 914891d commit ad0b0bc809c228f636cbabb534b158372d436ae7 @jsl committed
Showing with 16 additions and 18 deletions.
  1. +4 −0 README.md
  2. +12 −18 lib/baby_sim/thing.rb
View
4 README.md
@@ -12,3 +12,7 @@ To run, download Shoes for your operating system and open the lib/baby_sim/baby_
To configure the baby's environment, change the DSL in lib/baby_sim.rb in order to change object
quantities or add other objects to the environment.
+
+## Notes
+
+Please don't follow this code for best practices - it's being used in a talk about uses and abuses of meta-programming. It shouldn't be used as an example of good programming nor should it be used in any way for child-rearing. ;)
View
30 lib/baby_sim/thing.rb
@@ -1,5 +1,6 @@
module BabySim
class Thing
+ ATTRIBUTE_METHODS = [:color, :effect, :count, :message]
@@all = []
@@ -12,33 +13,26 @@ def self.all
def initialize name, &block
@name = name
@message = nil
+ @count = 0
+ @effect = 0
instance_eval &block
@@all << self
end
- def color(new_color = nil)
- set_or_get(:color, new_color)
+ def respond_to?(symbol)
+ ATTRIBUTE_METHODS.include?(symbol) || super
end
- def effect(new_effect = nil)
- set_or_get(:effect, new_effect)
- end
-
- def count(new_count = nil)
- set_or_get(:count, new_count)
- end
-
- def message(new_message = nil)
- set_or_get(:message, new_message)
- end
-
- private
+ def method_missing(meth, *args, &block)
+ if ATTRIBUTE_METHODS.include?(meth)
+ variable = :"@#{meth}"
+ args.any? ? instance_variable_set(variable, args[0]) : instance_variable_get(variable)
+ else
+ super
+ end
- def set_or_get(key, value)
- instance_var = :"@#{key}"
- value.nil? ? instance_variable_get(instance_var) : instance_variable_set(instance_var, value)
end
end
end

0 comments on commit ad0b0bc

Please sign in to comment.
Something went wrong with that request. Please try again.