Enabling rails codelens navigation in neovim with ruby_lsp
I’ve moved over entirely to using neovim for my rails development, with the ruby_lsp integration with neovim making it a real pleasure. This includes ‘luxury’ features I’d previously seen in GUI IDEs, like codelens annotations, which allow you to see the route signature for a given action amongst other things:
One thing was irking me though. Whilst the codelens annotations were displaying, I couldn’t follow the links to the relevant view or route.rb entry using <leader>cc
(“Run Codelens”), as you can do in vscode. Neovim threw the error:
Language server `ruby_lsp` does not support command `rubyLsp.openFile`. This command may require a client extension.
Adding a custom command handler to handle codelens navigation
With a bit of digging, it turns out that this is a command issued back by the LSP to neovim, and it needs specific handling in order to navigate to files. So I crafted a simple handler to take you to the correct file and (if provided) line, and added it to my lazyvim plugins config (lua/plugins/nvim-lspconfig.lua
):
return {
{
"neovim/nvim-lspconfig",
opts = {
codelens = {
enabled = true,
},
setup = {
ruby_lsp = function(_, _)
vim.lsp.commands["rubyLsp.openFile"] = function(cmd, _)
local uri_frag = cmd.arguments[1][1]
local uri, line = uri_frag:match("^(.+)#L(%d+)$")
if not uri then
uri = uri_frag
end
local bufnr = vim.uri_to_bufnr(uri)
vim.fn.bufload(bufnr)
vim.api.nvim_set_option_value("buflisted", true, { buf = bufnr })
vim.api.nvim_set_current_buf(bufnr)
vim.api.nvim_win_set_cursor(0, { tonumber(line) or 1, 0 })
end
end,
},
},
},
}
Now I can easily jump to route definitions and views from my controllers.