added Invoker mixin

This commit is contained in:
kikito 2010-09-20 23:36:28 +02:00
parent 4bd787b799
commit c43be70678
2 changed files with 64 additions and 0 deletions

View File

@ -0,0 +1,38 @@
-----------------------------------------------------------------------------------
-- Invoker.lua
-- Enrique García ( enrique.garcia.cota [AT] gmail [DOT] com ) - 4 Mar 2010
-- Helper function that simplifies method invocation via method names or functions
-----------------------------------------------------------------------------------
--[[ Usage:
require 'middleclass.mixins.Invoker' -- or 'middleclass.init'
MyClass = class('MyClass')
MyClass:includes(Invoker)
function MyClass:foo(x,y) print('foo executed with params', x, y) end
local obj = MyClass:new()
obj:invoke('foo', 1,2) -- foo executed with params 1 2
obj:invoke( function(self, x, y)
print('nameless function executed with params', x, y)
, 3, 4) -- nameless function executed with params 3, 4
Note that the function first parameter will allways be self
]]
assert(Object~=nil and class~=nil, 'MiddleClass not detected. Please require it before using Beholder')
Invoker = {
invoke = function(self, methodOrName, ...)
local method = methodOrName
if(type(methodOrName)=='string') then method = self[methodOrName] end
assert(type(method)=='function', 'Invoker:invoke requires a function or function name')
return method(self, ...)
end
}

26
spec/Invoker_spec.lua Normal file
View File

@ -0,0 +1,26 @@
require('middleclass.init')
context( 'Invoker', function()
local MyClass = class('MyClass')
MyClass:include(Invoker)
function MyClass:foo(x,y) return 'foo ' .. tostring(x) .. ', ' .. tostring(y) end
local obj = MyClass:new()
test('It should work with method names', function()
assert_equal(obj:invoke('foo', 1, 2), 'foo 1, 2')
end)
test('It should work with implicit functions', function()
assert_equal(
obj:invoke(
function(self, x, y) return 'bar '.. tostring(x) .. ', ' .. tostring(y) end,
3,
4
),
'bar 3, 4'
)
end)
end)