Module: Metro::KeyValueCoding

Included in:
Model
Defined in:
lib/metro/models/key_value_coding.rb

Overview

Key-Value coding emulates the functionality found in Objective-C, which allows for an object to be sent a message which contains the method to return. This is the same as Ruby. However, Objective-C also supports the use of the dot notation within the keys to acces the sub-values.

Examples:

Setting the red value of the color on a Model.


class Elf
  include KeyValueCoding

  attr_accessor :color
end

elf = Elf.new
elf.color = Gosu::Color.new "rgb(0,0,0)"

elf.get("color.red")      # => 0
elf.set("color.red",255)
elf.get("color.red")      # => 255

Instance Method Summary collapse

Instance Method Details

#get(name) ⇒ Object



32
33
34
35
# File 'lib/metro/models/key_value_coding.rb', line 32

def get(name)
  keys = name.to_s.split('.')
  keys.inject(self) {|target,method| target.send(method) }
end

#set(name, value) ⇒ Object



26
27
28
29
30
# File 'lib/metro/models/key_value_coding.rb', line 26

def set(name,value)
  keys = name.to_s.split('.')
  key_to_set = keys[0..-2].inject(self) {|target,method| target.send(method) }
  key_to_set.send("#{keys.last}=",value)
end