diff --git a/middleclass/mixins/Invoker.lua b/middleclass/mixins/Invoker.lua new file mode 100644 index 0000000..6dde6c9 --- /dev/null +++ b/middleclass/mixins/Invoker.lua @@ -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 + +} + + diff --git a/spec/Invoker_spec.lua b/spec/Invoker_spec.lua new file mode 100644 index 0000000..44cf967 --- /dev/null +++ b/spec/Invoker_spec.lua @@ -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)