Skip to content

Commit

Permalink
Use method-missing
Browse files Browse the repository at this point in the history
  • Loading branch information
jsl committed Jul 21, 2012
1 parent 914891d commit ad0b0bc
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 18 deletions.
4 changes: 4 additions & 0 deletions README.md
Expand Up @@ -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. ;)
30 changes: 12 additions & 18 deletions lib/baby_sim/thing.rb
@@ -1,5 +1,6 @@
module BabySim
class Thing
ATTRIBUTE_METHODS = [:color, :effect, :count, :message]

@@all = []

Expand 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.