[Code] wrapping operations
-
ALWAYS use a
begin
..rescue
..end
block for your operation.If an error occurs, the operation can be aborted, and (hopefully,) prevent corruption of the model.
begin op_name = "My Operation" model.start_operation( op_name ) # ### indented code statements here # model.commit_operation rescue => e model.abort_operation puts("Error #<#{e.class.name};#{e.message}.>") puts(e.backtrace) if $VERBOSE else # # Do code here ONLY if NO errors occur. # ensure # # ALWAYS do code here errors or not. # end
-
Thanks.
/Joel
-
Dan,
thanks for this. It works. I don't know why though!
Best,
Francis -
@francis mc shane said:
Dan,
thanks for this. It works. I don't know why though!http://ruby-doc.org/core-2.0.0/doc/syntax/exceptions_rdoc.html
Ya should probably read the docs on page
http://ruby-doc.org/core-2.0.0/index.html
from "doc/syntax.rdoc" on down. There is only 11. -
One can also wrap Dan's code in a method
def self.operation(opName, procElse = nil, procEnsure = nil) if (block_given? && String === opName) am = Sketchup.active_model begin am.start_operation(opName, true) yield am.commit_operation rescue => e am.abort_operation puts("Error operation block #<#{e.class.name};#{e.message}.>") puts(e.backtrace) if $VERBOSE else procElse.call() if (Proc === procElse) ensure procEnsure.call() if (Proc === procEnsure) end else raise "Error operation parameters - No block given or opName not a String!" end end # call by # operation("My operation") { operation block }
Note that if either procElse and procEnsure are used, they should probably be lambdas. One should also be careful about return statements in the block passed to the method.
BTW, I'll use snake case for methods, maybe not variables...
Greg
Advertisement