It sounds more like you want to create a tool.
See the UI::Tool class in the API.
Then read through and understand the "linetool.rb" script in the "Plugins/Examples" directory.
Keep in mind that scripting within a GUI application's process, is event-driven programming, not a linear sequential exercise.
You write a class with callback methods, that the application calls, in response to UI input, mouse movements, key presses, etc., from the user.