The Button.connect syntax in Genie - linux

I want to apply a certain behaviour to a label. When a lateral button is clicked, the corresponding label should rotate 90 degrees. It can be easily done in vala, but I can't discover the particular syntax on genie.
The vala code I am trying to reproduce comes from elementary OS getting started guide:
hello_button.clicked.connect(() =>
{
hello_label.label = "Hello World!";
hello_button.sensitive = false;
});
rotate_button.clicked.connect(() =>
{
rotate_label.angle = 90;
rotate_label.label = "Verbal";
rotate_button.sensitive = false;
});
I actually managed to reproduce almost entirely the code in Genie, for the exception of the rotation. Here is how far I got:
/* ANOTHER GTK EXPERIMENT WITH GENIE BASED ON ELEMENTARY INTRODUCTORY PAGE
** compile with valac --pkg gtk+03.0 layoutgtkexample.gs */
[indent=4]
uses Gtk
init
Gtk.init (ref args)
var window = new Gtk.Window()
window.title = "Hello World!"
window.set_border_width(12)
var layout = new Gtk.Grid ()
layout.column_spacing = 6
layout.row_spacing = 6
var hello_button = new Gtk.Button.with_label("Say Hello")
var hello_label = new Gtk.Label("Hello")
var rotate_button = new Gtk.Button.with_label ("Rotate")
var rotate_label = new Gtk.Label("Horizontal")
// add first row of widgets
layout.attach (hello_button, 0, 0, 1,1)
layout.attach_next_to (hello_label, hello_button, PositionType.RIGHT, 1, 1)
// add second row of widgets
layout.attach(rotate_button, 0,1,1,1)
layout.attach_next_to(rotate_label, rotate_button, PositionType.RIGHT, 1, 1)
window.add(layout)
hello_button.clicked.connect(hello_pushed)
rotate_button.clicked.connect(rotate_pushed)
window.destroy.connect(Gtk.main_quit)
window.show_all ()
Gtk.main ()
def hello_pushed (btn:Button)
btn.label = "Hello World!"
btn.sensitive = false
def rotate_pushed (btn:Button)
btn.label = "Vertical"
//btn.angle = 90
btn.sensitive = false

The problem is to do with where identifiers are valid and is known as "scope".
The Vala example makes use of an anonymous function, also called a lambda expression in Vala. An anonymous function can be a "closure", when the variables in the scope that defines the anonymous function are also available within the anonymous function. This is useful because the callback occurs after the original block of code has been run, but the variables are still available within the callback. So in the Vala example, where both the button and label are defined in the enclosing scope, the button and label are also available in the callback anonymous function.
Unfortunately Genie isn't able to parse anonymous functions as function arguments, in this case within the connect() call. Although some work has been done on this in 2015. So you have rightly used a function name instead. The problem is the callback only passes the button as an argument and not the adjacent label. So to make the label available within the callback function we could use a class:
/* ANOTHER GTK EXPERIMENT WITH GENIE BASED ON ELEMENTARY INTRODUCTORY PAGE
** compile with valac --pkg gtk+-3.0 layoutgtkexample.gs */
[indent=4]
uses Gtk
init
Gtk.init (ref args)
new RotatingButtonWindow( "Hello World!" )
Gtk.main ()
class RotatingButtonWindow:Window
_hello_label:Label
_rotate_label:Label
construct( window_title:string )
title = window_title
set_border_width(12)
var layout = new Grid ()
layout.column_spacing = 6
layout.row_spacing = 6
// add 'hello' row of widgets
var hello_button = new Button.with_label("Say Hello")
_hello_label = new Label("Hello")
layout.attach (hello_button, 0, 0, 1,1)
layout.attach_next_to (_hello_label, hello_button, PositionType.RIGHT, 1, 1)
// add 'rotate' row of widgets
var rotate_button = new Button.with_label ("Rotate")
_rotate_label = new Label("Horizontal")
layout.attach(rotate_button, 0,1,1,1)
layout.attach_next_to(_rotate_label, rotate_button, PositionType.RIGHT, 1, 1)
add(layout)
hello_button.clicked.connect(hello_pushed)
rotate_button.clicked.connect(rotate_pushed)
destroy.connect(Gtk.main_quit)
show_all ()
def hello_pushed (btn:Button)
_hello_label.label = "Hello World!"
btn.sensitive = false
def rotate_pushed (btn:Button)
_rotate_label.label = "Vertical"
_rotate_label.angle = 90
btn.sensitive = false
A few notes:
By placing the definitions of the _hello_label and _rotate_label within the scope of the class they become available to all the functions defined in the class. Definitions like this are often called "fields". The underscore means they are not available outside the class, so in the example you cannot access them from init
construct() is called when the object is created, in the example the line new RotatingButtonWindow( "Hello World!" ) instantiates the object. If you repeat the line you will have two separate windows, that is two instances of the RotatingButtonWindow data type
You will notice that the RotatingButtonWindow type is also defined as a Window type. This means it is adding more detail to the Gtk.Window class. This is why title and set_border_width() can be used within the new class. They have been "inherited" from the parent Gtk.Window class
By using the Gtk namespace with uses Gtk we don't need to prefix everything with Gtk
As your Gtk application gets more complex you probably want to look at GtkBuilder. That allows windows and widgets to be laid out in an external file. Then use GResource to build the file into the binary of your application so there is no need to distribute the UI file separately.

Related

How to evaluate a String which one like a classname.methodname in SoapUI with Groovy?

I have groovy code as below:
def randomInt = RandomUtil.getRandomInt(1,200);
log.info randomInt
def chars = (("1".."9") + ("A".."Z") + ("a".."z")).join()
def randomString = RandomUtil.getRandomString(chars, randomInt) //works well with this code
log.info randomString
evaluate("log.info new Date()")
evaluate('RandomUtil.getRandomString(chars, randomInt)') //got error with this code
I want to evaluate a String which one like a {classname}.{methodname} in SoapUI with Groovy, just like above, but got error here, how to handle this and make it works well as I expect?
I have tried as blew:
evaluate('RandomUtil.getRandomString(chars, randomInt)') //got error with this code
Error As below:
Thu May 23 22:26:30 CST 2019:ERROR:An error occurred [No such property: getRandomString(chars, randomInt) for class: com.hypers.test.apitest.util.RandomUtil], see error log for details
The following code:
log = [info: { println(it) }]
class RandomUtil {
static def random = new Random()
static int getRandomInt(int from, int to) {
from + random.nextInt(to - from)
}
static String getRandomString(alphabet, len) {
def s = alphabet.size()
(1..len).collect { alphabet[random.nextInt(s)] }.join()
}
}
randomInt = RandomUtil.getRandomInt(1, 200)
log.info randomInt
chars = ('a'..'z') + ('A'..'Z') + ('0'..'9')
def randomString = RandomUtil.getRandomString(chars, 10) //works well with this code
log.info randomString
evaluate("log.info new Date()")
evaluate('RandomUtil.getRandomString(chars, randomInt)') //got error with this code
emulates your code, works, and produces the following output when run:
~> groovy solution.groovy
70
DDSQi27PYG
Thu May 23 20:51:58 CEST 2019
~>
I made up the RandomUtil class as you did not include the code for it.
I think the reason you are seeing the error you are seeing is that you define your variables char and randomInt using:
def chars = ...
and
def randomInt = ...
this puts the variables in local script scope. Please see this stackoverflow answer for an explanation with links to documentation of different ways of putting things in the script global scope and an explanation of how this works.
Essentially your groovy script code is implicitly an instance of the groovy Script class which in turn has an implicit Binding instance associated with it. When you write def x = ..., your variable is locally scoped, when you write x = ... or binding.x = ... the variable is defined in the script binding.
The evaluate method uses the same binding as the implicit script object. So the reason my example above works is that I omitted the def and just typed chars = and randomInt = which puts the variables in the script binding thus making them available for the code in the evaluate expression.
Though I have to say that even with all that, the phrasing No such property: getRandomString(chars, randomInt) seems really strange to me...I would have expected No such method or No such property: chars etc.
Sharing the code for for RandomUtil might help here.

QTreeWidgetItem does not get Checked

I am trying to Check Tree items from a function after the Tree is initialized. Check marks never appear. I'm not sure if I need to 'refresh' the Tree or that I am not interacting with the right object.
I've read about this widget a lot and I see the same question more or less on several websites but the answers are 8+ years old, two pages of code or I just don't understand them.
What am I doing wrong here? Why are there no check marks showing up in the tree when I call checkActiveTreeItems()?
After a REST call, I want to update the checked items in the tree. This seems to be ok but the items never get checked.
def checkActiveTreeItems(self):
for label in self.transactie['transactie']['labels']:
test = QtWidgets.QTreeWidgetItem([label])
test.setCheckState(0, QtCore.Qt.Checked)
This is the function that creates the tree, I do not call it again after setting the QTreeWidgetItem to Checked in the function above.
def initTree(self):
print("initTree")
self.treeWidget = QtWidgets.QTreeWidget(self.gridLayoutWidget)
self.treeWidget.setSelectionMode(QtWidgets.QAbstractItemView.ContiguousSelection)
self.treeWidget.setObjectName("treeWidget")
inkomstenstructuur = requests.get(url="http://localhost:32769/_db/piekenpijp/incoming/inkomstenstructuur")
iscontent = json.loads(inkomstenstructuur.content)
self.inkomsten = iscontent
inkomstentree = QtWidgets.QTreeWidgetItem(["Inkomsten"])
for groep in iscontent:
child = QtWidgets.QTreeWidgetItem([groep['groep']])
inkomstentree.addChild(child)
for categorie in groep['categorien']:
child2 = QtWidgets.QTreeWidgetItem([categorie])
child2.setCheckState(0, QtCore.Qt.Unchecked)
child.addChild(child2)
uitgavenstructuur = requests.get(url="http://localhost:32769/_db/piekenpijp/incoming/uitgavenstructuur")
uscontent = json.loads(uitgavenstructuur.content)
self.uitgaven = uscontent
uitgaventree = QtWidgets.QTreeWidgetItem(["Uitgaven"])
for groep in uscontent:
child = QtWidgets.QTreeWidgetItem([groep['groep']])
uitgaventree.addChild(child)
for categorie in groep['categorien']:
child2 = QtWidgets.QTreeWidgetItem([categorie])
child2.setCheckState(0, QtCore.Qt.Unchecked)
child.addChild(child2)
self.treeWidget.itemChanged.connect(self.vinkje)
self.treeWidget.resize(500, 200)
self.treeWidget.setColumnCount(1)
self.treeWidget.setHeaderLabels(["Categorie"])
self.treeWidget.addTopLevelItem(inkomstentree)
self.treeWidget.addTopLevelItem(uitgaventree)
self.treeWidget.expandItem(uitgaventree)
self.gridLayout.addWidget(self.treeWidget, 0, 2, 1, 1)
Your current method creates a new item, sets its check-state, and then throws it away without using it. Instead, you need to find the items in the tree that you have already created:
def checkActiveTreeItems(self):
for label in self.transactie['transactie']['labels']:
for item in self.treeWidget.findItems(label, Qt.MatchExactly):
item.setCheckState(0, QtCore.Qt.Checked)

Access COM methods from Python

I have an old Windows DLL, without source code, who implement a table of utility functions. Years ago it was planned to convert it in a COM object so an IUnknown interface was implemented. To work with this DLL, there is a header file (simplified):
interface IFunctions : public IUnknown
{
virtual int function1(int p1, int p2) = 0;
virtual void function2(int p1) = 0;
// and the likes ...
}
But no CLSID was defined for IFunctions interface. And eventually the interface definition in header file is non-compliant with COM standard.
From C++ the DLL can be loaded with
CoCreateInstance(clsid, 0, CLSCTX_INPROC_SERVER, clsid, ptr);
and with some pointer arithmetic from 'ptr' I find the addresses of funcion1(), etc. Since it worked, no complete COM implementation were done so I cannot QueryInterface for IFunctions interface because the interface is not a COM interface. In Windows Registry I find only the CLSID of the object and a reference to the DLL as it InprocServer32.
I do not have much experience in Python, but I need to use this DLL from Python, perhaps using ctypes and comtypes. I can load the DLL with (CLSID from registry)
unk = CreateObject('{11111111-2222-3333-4444-555555555555}', clsctx=comtypes.CLSCTX_INPROC_SERVER)
I know that in the VTable of the COM object function1() address is just after QueryInterface(), AddRef(), Release() but I cannot find a solution to implement a class like:
class DllFunction:
# not necessary, but for completeness ...
def QueryInterface(self, interface, iid=None):
return unk.QueryInterface(comtypes.IUnknown)
def AddRef(slef):
return unk.AddRef()
def Release(self):
return unk.Release()
# Functions I actually need to call from Python
def Function1(self, p1, p2):
# what to do ??
def Function2(self, p1):
# etc.
I would like to implement this solution in Python trying to avoid the development of an extension module in C++.
Thanks for any help.
Thanks to who provided some hints. Actually I cannot fix the DLL because I do not have the source code. Wrapping it in C++ was an option, but developing a wrapping Python module in C sounds better.
My plan was to use Python only, possibly without additional modules, so I managed to solve the issue using only ctypes. The following code show the solution. It works, but it needs some improvements (error checking, etc).
'''
Simple example of how to use the DLL from Python on Win32.
We need only ctypes.
'''
import ctypes
from ctypes import *
'''
We need a class to mirror GUID structure
'''
class GUID(Structure):
_fields_ = [("Data1", c_ulong),
("Data2", c_ushort),
("Data3", c_ushort),
("Data4", c_ubyte * 8)]
if __name__ == "__main__":
'''
COM APIs to activate/deactivate COM environment and load the COM object
'''
ole32=WinDLL('Ole32.dll')
CoInitialize = ole32.CoInitialize
CoUninitialize = ole32.CoUninitialize
CoCreateInstance = ole32.CoCreateInstance
'''
COM environment initialization
'''
rc = CoInitialize(None)
'''
To use CoCreate Instance in C (not C++):
void * driver = NULL;
rc = CoCreateInstance(&IID_Driver, // CLSID of the COM object
0, // no aggregation
CLSCTX_INPROC_SERVER, // CLSCTX_INPROC_SERVER = 1
&IID_Driver, // CLSID of the required interface
(void**)&driver); // result
In Python it is:
'''
clsid = GUID(0x11111111, 0x2222, 0x3333,
(0x44, 0x44, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55))
drv = c_void_p(None)
rc = CoCreateInstance(byref(clsid), 0, 1, byref(clsid), byref(drv))
'''
Pointers manipulation. Short form:
function = cast( c_void_p( cast(drv, POINTER(c_void_p))[0] ), POINTER(c_void_p))
'''
VTable = cast(drv, POINTER(c_void_p))
wk = c_void_p(VTable[0])
function = cast(wk, POINTER(c_void_p))
#print('VTbale address: ', hex(VTable[0]))
#print('QueryInterface address: ', hex(function[0]))
#print('AddRef address: ', hex(function[1]))
#print('Release address: ', hex(function[2]))
'''
To define functions from their addresses we first need to define their WINFUNCTYPE.
In C we call QueryInterface:
HRESULT rc = driver->lpVtbl->QueryInterface(driver, &IID_IUnknown, (void**)&iUnk);
So we need a long (HRESULT) return value and three pointers. It would be better to be
more accurate in pointer types, but ... it works!
We can use whatever names we want for function types and functions
'''
QueryInterfaceType = WINFUNCTYPE(c_long, c_void_p, c_void_p, c_void_p)
QueryInterface = QueryInterfaceType(function[0])
AddRefType = WINFUNCTYPE(c_ulong, c_void_p)
AddRef = AddRefType(function[1])
ReleaseType = WINFUNCTYPE(c_ulong, c_void_p)
Release = ReleaseType(function[2])
'''
The same for other functions, but library functions do not want 'this':
long rc = driver->lpVtbl->init(0);
'''
doThisType = WINFUNCTYPE(c_long, c_void_p)
doThis=doThisType(function[3])
getNameType = WINFUNCTYPE(c_int, c_char_p)
getName = getNameType(function[4])
getName.restype = None # to have None since function is void
getVersionType = WINFUNCTYPE(c_long)
getVersion = getVersionType(function[5])
getMessageType = WINFUNCTYPE(c_int, c_char_p)
getMessage = getMessageType(function[6])
getMessage.restype = None # to have None since function is void
'''
Now we can use functions in plain Python
'''
rc = doThis(0)
print(rc)
name = create_string_buffer(128)
rc = getName(name)
print(rc)
print(name.value)
ver = getVersion()
print(ver)
msg = create_string_buffer(256)
rc = getMessage(msg)
print(rc)
print(msg.value)
'''
Unload DLL and reset COM environment
'''
rc = Release(drv)
rc = CoUninitialize()
print("Done!")
I hope this example will be useful to somebody. It can be used to wrap a COM object without comtypes and, to me, clarify how ctypes works.

Soapui Groovy - No Signature of Method error on ProWsdlTestSuitePanelBuilder.buildDesktopPanel

I'm working on a script to automate the running of several TestSuites across multiple projects concurrently in SoapUI 4.5.1:
import com.eviware.soapui.impl.wsdl.panels.testsuite.*;
def properties = new com.eviware.soapui.support.types.StringToObjectMap();
def currentProject = testRunner.getTestCase().testSuite.getProject();
def workspace = currentProject.getWorkspace();
def otherProject = workspace.getProjectByName('Project 1');
def otherTestSuite = CGReportsProject.getTestSuiteByName('TestSuite 1');
otherTestSuite.run(properties, true);
However, I'm also attempting to open the TestSuite Panel for each of the TestSuites that are run by the script to allow visual tracking of the Suites' progress. That's where I run into trouble:
ProWsdlTestSuitePanelBuilder.buildDesktopPanel(otherTestSuite);
This particular line throws the error:
groovy.lang.MissingMethodException: No signature of method:
static com.eviware.soapui.impl.wsdl.panels.testsuite.
ProWsdlTestSuitePanelBuilder.buildDesktopPanel() is
applicable for argument types:
(com.eviware.soapui.impl.wsdl.WsdlTestSuitePro) values:
[com.eviware.soapui.impl.wsdl.WsdlTestSuitePro#1d0b2bc6]
Possible solutions:
buildDesktopPanel(com.eviware.soapui.impl.wsdl.WsdlTestSuitePro),
buildDesktopPanel(com.eviware.soapui.model.ModelItem),
buildDesktopPanel(com.eviware.soapui.impl.wsdl.WsdlTestSuite),
buildDesktopPanel(com.eviware.soapui.model.ModelItem),
buildDesktopPanel(com.eviware.soapui.impl.wsdl.WsdlTestSuite),
buildDesktopPanel(com.eviware.soapui.model.ModelItem)
error at line: 12
Which I take to mean that the instance of the WsdlTestSuitePro I'm throwing at ProWsdlTestSuitePanelBuilder.buildDesktopPanel() isn't being accepted for some reason - but I've no idea why.
At this point, I'm also not sure if the ProWsdlTestSuitePanelBuilder.buildDesktopPanel() is really what I want anyway, but it's the only UI builder that'll take a WsdlTestSuitePro, as that apparently what all my Testsuites are.
Okay, so this falls under the newbie catagory. I wasn't paying attention to the fact that buildDesktopPanel was static.
However, I managed to work around that and create the final product:
// Create a UISupport container for all the panels we'll be showing
def UIDesktop = new com.eviware.soapui.support.UISupport();
// Basic environment information
def properties = new com.eviware.soapui.support.types.StringToObjectMap();
def currentProject = testRunner.getTestCase().testSuite.getProject();
def workspace = currentProject.getWorkspace();
// Get the various Projects we'll be using
def OtherProject = workspace.getProjectByName('Other Project');
// Get the various TestSuites we'll be running
def OtherTestSuite = OtherProject.getTestSuiteByName('Other Test Suite');
// Generate the Panels for the Testsuites
def TestSuitePanel = new com.eviware.soapui.impl.wsdl.panels.testsuite.ProWsdlTestSuiteDesktopPanel(OtherTestSuite);
// Show TestSuite Panels
UIDesktop.showDesktopPanel(TestSuitePanel);
// Run the Testsuites
OtherTestSuite.run(properties, true);

Are there equivalents to Ruby's method_missing in other languages?

In Ruby, objects have a handy method called method_missing which allows one to handle method calls for methods that have not even been (explicitly) defined:
Invoked by Ruby when obj is sent a message it cannot handle. symbol is the symbol for the method called, and args are any arguments that were passed to it. By default, the interpreter raises an error when this method is called. However, it is possible to override the method to provide more dynamic behavior. The example below creates a class Roman, which responds to methods with names consisting of roman numerals, returning the corresponding integer values.
class Roman
def romanToInt(str)
# ...
end
def method_missing(methId)
str = methId.id2name
romanToInt(str)
end
end
r = Roman.new
r.iv #=> 4
r.xxiii #=> 23
r.mm #=> 2000
For example, Ruby on Rails uses this to allow calls to methods such as find_by_my_column_name.
My question is, what other languages support an equivalent to method_missing, and how do you implement the equivalent in your code?
Smalltalk has the doesNotUnderstand message, which is probably the original implementation of this idea, given that Smalltalk is one of Ruby's parents. The default implementation displays an error window, but it can be overridden to do something more interesting.
PHP objects can be overloaded with the __call special method.
For example:
<?php
class MethodTest {
public function __call($name, $arguments) {
// Note: value of $name is case sensitive.
echo "Calling object method '$name' "
. implode(', ', $arguments). "\n";
}
}
$obj = new MethodTest;
$obj->runTest('in object context');
?>
Some use cases of method_missing can be implemented in Python using __getattr__ e.g.
class Roman(object):
def roman_to_int(self, roman):
# implementation here
def __getattr__(self, name):
return self.roman_to_int(name)
Then you can do:
>>> r = Roman()
>>> r.iv
4
I was looking for this before, and found a useful list (quickly being overtaken here) as part of the Merd project on SourceForge.
Construct Language
----------- ----------
AUTOLOAD Perl
AUTOSCALAR, AUTOMETH, AUTOLOAD... Perl6
__getattr__ Python
method_missing Ruby
doesNotUnderstand Smalltalk
__noSuchMethod__(17) CoffeeScript, JavaScript
unknown Tcl
no-applicable-method Common Lisp
doesNotRecognizeSelector Objective-C
TryInvokeMember(18) C#
match [name, args] { ... } E
the predicate fail Prolog
forward Io
With footnotes:
(17) firefox
(18) C# 4, only for "dynamic" objects
JavaScript has noSuchMethod, but unfortunately this is only supported by Firefox/Spidermonkey.
Here is an example:
wittyProjectName.__noSuchMethod__ = function __noSuchMethod__ (id, args) {
if (id == 'errorize') {
wittyProjectName.log("wittyProjectName.errorize has been deprecated.\n" +
"Use wittyProjectName.log(message, " +
"wittyProjectName.LOGTYPE_ERROR) instead.",
this.LOGTYPE_LOG);
// just act as a wrapper for the newer log method
args.push(this.LOGTYPE_ERROR);
this.log.apply(this, args);
}
}
Perl has AUTOLOAD which works on subroutines & class/object methods.
Subroutine example:
use 5.012;
use warnings;
sub AUTOLOAD {
my $sub_missing = our $AUTOLOAD;
$sub_missing =~ s/.*:://;
uc $sub_missing;
}
say foo(); # => FOO
Class/Object method call example:
use 5.012;
use warnings;
{
package Shout;
sub new { bless {}, shift }
sub AUTOLOAD {
my $method_missing = our $AUTOLOAD;
$method_missing =~ s/.*:://;
uc $method_missing;
}
}
say Shout->bar; # => BAR
my $shout = Shout->new;
say $shout->baz; # => BAZ
Objective-C supports the same thing and calls it forwarding.
This is accomplished in Lua by setting the __index key of a metatable.
t = {}
meta = {__index = function(_, idx) return function() print(idx) end end}
setmetatable(t, meta)
t.foo()
t.bar()
This code will output:
foo
bar
In Common Lisp, no-applicable-method may be used for this purpose, according to the Common Lisp Hyper Spec:
The generic function no-applicable-method is called when a generic function is invoked and no method on that generic function is applicable. The default method signals an error.
The generic function no-applicable-method is not intended to be called by programmers. Programmers may write methods for it.
So for example:
(defmethod no-applicable-method (gf &rest args)
;(error "No applicable method for args:~% ~s~% to ~s" args gf)
(%error (make-condition 'no-applicable-method :generic-function gf :arguments args) '()
;; Go past the anonymous frame to the frame for the caller of the generic function
(parent-frame (%get-frame-ptr))))
C# now has TryInvokeMember, for dynamic objects (inheriting from DynamicObject)
Actionscript 3.0 has a Proxy class that can be extended to provide this functionality.
dynamic class MyProxy extends Proxy {
flash_proxy override function callProperty(name:*, ...rest):* {
try {
// custom code here
}
catch (e:Error) {
// respond to error here
}
}
Tcl has something similar. Any time you call any command that can't be found, the procedure unknown will be called. While it's not something you normally use, it can be handy at times.
In CFML (ColdFusion, Railo, OpenBD), the onMissingMethod() event handler, defined within a component, will receive undefined method calls on that component. The arguments missingMethodName and missingMethodArguments are automatically passed in, allowing dynamic handling of the missing method call. This is the mechanism that facilitated the creation of implicit setter/getter schemes before they began to be built into the various CFML engines.
Its equivalent in Io is using the forward method.
From the docs:
If an object doesn't respond to a message, it will invoke its "forward" method if it has one....
Here is a simple example:
Shout := Object clone do (
forward := method (
method_missing := call message name
method_missing asUppercase
)
)
Shout baz println # => BAZ
/I3az/
Boo has IQuackFu - there is already an excellent summary on SO at how-can-i-intercept-a-method-call-in-boo
Here is an example:
class XmlObject(IQuackFu):
_element as XmlElement
def constructor(element as XmlElement):
_element = element
def QuackInvoke(name as string, args as (object)) as object:
pass # ignored
def QuackSet(name as string, parameters as (object), value) as object:
pass # ignored
def QuackGet(name as string, parameters as (object)) as object:
elements = _element.SelectNodes(name)
if elements is not null:
return XmlObject(elements[0]) if elements.Count == 1
return XmlObject(e) for e as XmlElement in elements
override def ToString():
return _element.InnerText

Resources