Html dialog box to set and get information

You actually send arrays and hashes to the dialog’s JavaScript as JSON text.

It is really easy. At the top of your code you can ensure the Ruby JSON library is loaded like this …

require 'json' unless defined? JSON
ruby_ary = [ [1, 2, 3 ], [9, 4, 6], [4, 6, 8] ]
# dialog is your UI::HtmlDialog object
json = ruby_ary.to_json
dialog.execute_script( %[var js_ary = JSON.parse('#{json}');] )

Of course the variable names can be whatever you wish, and be the same or different on each side (ie, the “Ruby-side” and the “JavaScript-side”.)

The %[text] (or %Q[text],) is a Ruby double quoted string syntax that does interpolation.
(The %q[text] syntax is a single quoted string that does not do interpolation.)
We use them because JavaScript code often needs to have quotes in it, so these special String syntax allow us to use quotes within them. ( See: Ruby Syntax: Literals - Strings )

Anyway … you can also easily pass more complex and robust data such as a Ruby Hash, Struct or OpenStruct over to the dialog as JavaScript objects.

json = dyna_hash.to_json
dialog.execute_script( %[var my_obj = JSON.parse('#{json}');] )

We use single quotes around the JSON.parse method argument because JSON text uses double quotes internally around strings and member names.

ADD: We can also send SketchUp Ruby AttributeDictionary object data over quite easily because they have Ruby’s Enumerable module mixed in, which gives them a #to_h method to produce a Hash.

# Where dict is a reference to some attribute dictionary:
dict = comp_inst.attribute_dictionary("dynamic_attributes")
json = dict.to_h.to_json
dialog.execute_script( %[var dict_inst = JSON.parse('#{json}');] )
dict = comp_inst.definition.attribute_dictionary("dynamic_attributes")
json = dict.to_h.to_json
dialog.execute_script( %[var dict_defn = JSON.parse('#{json}');] )

(You should of course, check that the attribute dictionary getter calls do not return nil.)

1 Like