Hello Matthias,
I am having some trouble creating my own method. Can you tell me why this code keeps saying that "my_method" is undefined? There is a concept that I must not understand.
module MyMacro
include RBA
my_method(10000,10000)
def my_method(x,y)
mw = RBA::Application::instance.main_window
layout = mw.create_layout(0).layout
layout_view = mw.current_view
my_cell = layout.add_cell("My_Cell")
cell = layout.cell(my_cell)
layer = layout.insert_layer(RBA::LayerInfo::new(1,0))
cell.shapes(layer).insert(RBA::Box::new(-x,-y,x,y))
layout_view.select_cell(my_cell, 0)
layout_view.add_missing_layers
layout_view.zoom_fit
end
end
Comments
Hi Jared,
Ruby is not a compiler language which uses the linker to resolve the target of a call. "def" is a statement like every other statement. Ruby runs the script once and while execution the function call, the function is not defined yet.
Just put the function definition in front of the call and it should work.
Regards,
Matthias
Hi Jared,
sorry, I missed one important thing: inside a Module you need to write functions as class methods of the Module, i.e.
The reason for that is not easy to explain in terms of a usual scripting language. Frankly, the procedural script style we are using inside KLayout scripts is not really "Ruby like". Ruby modules are intended for other purposes than providing a namespace and allowing the "include RBA" trick without nasty side effects.
"Real ruby" would be like this:
That looks somewhat unfamiliar and there is no apparent advantage of this style (except encapsulation and all the other nice things that come along with OO style of programming ...). But it demonstrates what is happening: f is actually an instance method and hence it can only be called from an instance, i.e. after "new". Modules basically behave like classes but you cannot create an instance of a module. Modules are mainly intended to be mixed into classes in the sense of "add-ons" for classes. But the basic concepts are the same.
Code inside the module definition is executed in the scope of the module class, not the module instance. Hence you can only call class methods. "def" without qualifier defines an instance method, which - lacking the instance - you cannot call. "def self.f ..." is the way to define a class method (in C++ terms a "static" method).
In case you wonder why this works outside a module without the "self.": there the code is executed in the scope of an object instance called "main". Using "def" will create an instance method which is fine because the code is already executed inside the instance.
I hope this makes the issue somewhat clearer. Ruby just looks like a usual procedural language such as Perl, but in fact it's quite different with exciting new possibilities.
Regards,
Matthias