Created
November 17, 2011 19:18
-
-
Save hellopatrick/1374142 to your computer and use it in GitHub Desktop.
Indexed KVO-Compliance & MacRuby
This file contains hidden or 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 Object | |
def self.attr_indexed var, custom_methods = {} | |
key = var.to_s | |
capitalized_key = key.capitalize[0] + key[1..-1] | |
methods = { | |
:size => lambda { instance_variable_get("@#{var}").size }, | |
:at => lambda { |idx| instance_variable_get("@#{var}")[idx] }, | |
:insert => lambda { |obj, idx| instance_variable_get("@#{var}").insert(idx, obj) }, | |
:delete_at => lambda { |idx| instance_variable_get("@#{var}").delete_at(idx) } | |
}.merge custom_methods | |
define_method :"countOf#{capitalized_key}", methods[:size] | |
define_method :"objectIn#{capitalized_key}AtIndex:", methods[:at] | |
# define_method :"insertObject:in#{capitalized_key}AtIndex:", methods[:insert] | |
# define_method :"removeObjectFrom#{capitalized_key}AtIndex:", methods[:delete_at] | |
end | |
end | |
class Test | |
def initialize | |
@squares = [0, 1, 4, 9, 16] | |
end | |
# backed by Array | |
attr_indexed :squares | |
# backed by custom methods | |
attr_indexed :naturalNumbers, { | |
:size => lambda { 4 }, | |
:at => lambda {|i| i } | |
} | |
# just straight KVO compliance | |
def countOfCubes; 6; end | |
def objectInCubesAtIndex(idx); idx ** 3; end | |
end | |
test = Test.new | |
# this is all correct | |
puts "count of natural numbers: #{test.countOfNaturalNumbers} == 4" | |
puts "count of squares: #{test.countOfSquares} == 5" | |
puts "count of cubes: #{test.countOfCubes} == 6" | |
# as are these... | |
puts "natural: #{test.objectInNaturalNumbersAtIndex(0)} == 0" | |
puts "squares: #{test.objectInSquaresAtIndex(3)} == 3 ** 2" | |
puts "cubes: #{test.objectInCubesAtIndex(5)} == 5 ** 3" | |
# this will fail, uncomment to fail. | |
puts "#{test.valueForKey("naturalNumbers")} == #{(0...4).to_a}" | |
puts "#{test.valueForKey("squares")} == #{(0...5).map { |i| i ** 2}}" | |
# this will work | |
puts "#{test.valueForKey("cubes")} == #{(0...6).map { |i| i ** 3}}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment