mirror of
https://github.com/kikito/middleclass.git
synced 2024-11-08 09:34:22 +00:00
added Invoker mixin
This commit is contained in:
parent
4bd787b799
commit
c43be70678
38
middleclass/mixins/Invoker.lua
Normal file
38
middleclass/mixins/Invoker.lua
Normal 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
26
spec/Invoker_spec.lua
Normal 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)
|
Loading…
Reference in New Issue
Block a user