Using Ruby Libraries from SketchUp

I found this short plugin - it's an RSS reader plugin for SketchUp. Why, you ask? I have no idea, but the author uses some interesting techniques worth noting.

$LOAD_PATH << 'C:\ruby\lib\ruby\1.8'

This line appends the ruby library path to SketchUp Ruby's global $LOAD_PATH variable. Now, SU will look in the appended folder for required files; as demonstrated by the next 2 lines:

require 'rss/1.0'
require 'rss/2.0'

The other interesting thing the author does is use open-uri to open and read a document from the Internet into a string:

source = `ruby -r 'open-uri' -e 'puts open("#{uri}").read'`

This code calls the external ruby to do the work. The -r option is equivalent to "require 'open-uri'". The -e means execute the following stuff. So, SketchUp's built-in Ruby is executing the external ruby, which prints the web page to standard out. The ` (backtick?) command in Ruby captures the output, which is then assigned to the "source" variable inside SketchUp. Clever.

Note that instead of the backticks, the author could have used:

%x{ ... }

which is synonymous with the ` ... ` syntax. I would recommend using this syntax as it will help avoid too-many-quotes syndrome.

Here's another example:

page=%x{ruby -r 'uri' -r 'net/http' -e 'Net::HTTP.get_print URI.parse("")'}

which you can probably guess what it does.

Although this technique does work, I don't think it's an optimal solution. First off, you will need to have the full Ruby installed on your computer, and there's no guarantee that your plugin's users will have it.

No comments:

Popular Posts (Last 30 Days)