Vim function to calculate ruby class definition wi

2019-09-06 09:20发布

问题:

I'd like to start using vimscript to automate some more complicated parts of my workflow. I'm looking for a concrete advanced example to get me started. How would you vim guru's implement the following?

I'm in an empty buffer for a file located at lib/foo/bar/buz.rb. I want to use my file context + a binding to insert the following into the buffer:

module Foo
module Bar

  class Buz
  end

end
end

What's the vim function look like?

Bonus: Vim function to update class definition to reflect current location

I think this example will take my vim scripting to the next level. Thanks!

回答1:

This is ultimately what I came up with.

" Generates a ruby class definition based on the current file's path
function! GenerateRubyClassDefinition()
  " parse file path
  let l:path = expand("%:.:r")
  let l:path = substitute(l:path, "lib/", "", "")
  let l:parts = split(l:path, "/")

  " extract parts
  let l:class_name = l:parts[-1]
  let l:module_names = l:parts[0:-2]

  " generate
  let l:output = ""

  " generate - module headers
  for m in l:module_names
    let l:output .= "module " . g:Abolish.mixedcase(m) . "\n"
  endfor

  " generate - class
  let l:output .= "\n"
  let l:output .= "  class " . g:Abolish.mixedcase(class_name) . "\n"
  let l:output .= "  end\n"
  let l:output .= "\n"

  " generate - module footers
  for m in l:module_names
    let l:output .= "end\n"
  endfor

  echo l:output
endfunction

The above snippet assumes you have tpope's vim-abolish plugin installed. This helps with the transformation of snakecase file paths into mixedcase object names.

Sourcing the above and calling :GenerateRubyClassDefinition() from an open file buffer will echo the target output.