Search code examples
regexvscode-snippets

Transfom file path into Ruby nested Class using regex syntax transform


I try to change this (VSCode RELATIVE_FILEPATH variable):

app/service/namespace/important_thing/my_class.rb

into this:

Namespace::ImportantThing::MyClass

What I got so far:

RELATIVE_FILEPATH/(?:\\/?app\\/\\w+)?(\\/|_)(.(?!\\w+?\\.rb))/::${2:/upcase}/g}:

but the result is not great

::Namespace::Importand::Thing/my_class.rb

I'm doing this to create myself a snippet but this regex is a little bit to much for me.

I've used something similar in Sublime but there it was done with some code in python so can't be referenced from there.


Solution

  • You can use

    "${RELATIVE_FILEPATH/^(?:.*?[\\\\\\/])?app[\\\\\\/]\\w+[\\\\\\/]|([^\\\\\\/]+?)(?:\\.rb$|([\\\\\\/]))/${1:/pascalcase}${2:+::}/g}"
    

    See the regex demo. Details:

    • ^(?:.*?[\\\/])?app[\\\/]\w+[\\\/] - start of string, any zero or more chars other than line break chars as few as possible, then \ or /, then an app, a \ or /, one or more word chars, \ or /
    • | - or
    • ([^\\\/]+?) - Group 1: one or more chars other than \ and / as few as possible
    • (?:\.rb$|([\\\/])) - a non-capturing group matching either .rb at the end of string, or \ / / (captured into Group 2).

    The replacement is ${1:/pascalcase}${2:+::}:

    • ${1:/pascalcase} - replace the match with Group 1 turned into PasCal case
    • ${2:+::} - if Group 2 matched, also add :: to the replacement.