File Path with Ruby API

I’ve been using this little snippet of code to determine the path to my various subfolders and files within my plugin folder:

# Fix for ruby 2.0
if this_dir.respond_to?(:force_encoding)

then something like this:

@Roof_osb_mat.texture = File.join(this_dir,'materials/WOOD_OSB.jpg')

Now I’ve decided to nest some of my ruby files within sub-folders but I still want to access this same content found in the materials folder. What would be the best way to do this?

I guess what I am trying to find is the parent of the this_dir.

One suggested solution is:

this_dir=File.dirname(File.expand_path('..', __FILE__))

I just set EXTENSION_DIR as a constant in the registrar file (the one living directly in the plugin folder) and use that constant everywhere I need absolute paths.

EDIT: And for clarification I do the encoding fix before setting the constant, meaning I only have to do that fix on one single place in the whole extension.


Using a constant and only having to do this once makes sense, not sure why I never set it up this way but I will fix all of my extensions moving forward. Thank-you for the guidance.

Might just use:

File.expand_path '../..', __FILE__

JFYI, I think (but I’m not totally sure), that __FILE__ will return the filename called. But, if a symlink was called, __dir__ will return the absolute path. Odd, but it gives one the choice of being able to get at both.

Use __dir__ if you only care about the path of the current file.

File.expand_path('../..', __dir__)

That being said, I do the same as Christina.
Though one thing against this is that it adds a dependency on that constant all over your source code. So if you reuse it in other projects you need to remember to have the constant defined before loading the rest of the files.

For require I use relative path based from the root location of the extension (Plugins folder).

1 Like

If I define the constant in my load.rb file then I should be covered. This file is run when the plugin is initiated at SketchUp startup.

1 Like