1

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.

1 Answers1

1

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.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Thanks! It works like a charm. The explanations also allowed me to learn something new! I was able to modify it and also use it in my _spec.rb files templates. – Dominik Alberski Jan 07 '22 at 14:03