Skip to content

Instantly share code, notes, and snippets.

@Sam-Serpoosh
Created February 24, 2014 23:37
Show Gist options
  • Save Sam-Serpoosh/9199578 to your computer and use it in GitHub Desktop.
Save Sam-Serpoosh/9199578 to your computer and use it in GitHub Desktop.
Switching between production and test file in the same directory back and forth! (Works for Ruby & Python)
function! OpenTestOrProduction()
let current_file_without_extension = expand("%:r")
let filename_parts = split(current_file_without_extension, "_")
let target_file = ""
if IsInTestFile()
let main_name_parts = filename_parts[0:-2]
let target_file = CreateTargeFilename(main_name_parts)
else
let target_file = CreateTargeTestFilename(current_file_without_extension)
end
call OpenFileForEditIfExists(target_file)
endfunction
function IsInTestFile()
let current_file = expand("%")
return match(current_file, '_spec.rb$') != -1 || match(current_file, '_tests.py$') != -1
endfunction
function CreateTargeFilename(filename_parts)
let extension = expand("%:e")
if extension == "rb"
return join(a:filename_parts, "_") . ".rb"
endif
return join(a:filename_parts, "_") . ".py"
endfunction
function CreateTargeTestFilename(filename_without_extension)
let extension = expand("%:e")
if extension == "rb"
return a:filename_without_extension . "_spec.rb"
endif
return a:filename_without_extension . "_tests.py"
endfunction
function! OpenFileForEditIfExists(filename)
if filereadable(a:filename)
exe "edit " . a:filename
else
echo "File: " . a:filename "does NOT exist!"
end
endfunction
@Sam-Serpoosh
Copy link
Author

You can map it to something like following:

**map <leader>o :call OpenTestOrProduction()<CR>**

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment