Last active
December 30, 2025 04:46
-
-
Save staycreativedesign/e808e15b235c944a261d28c7e93e1226 to your computer and use it in GitHub Desktop.
For RUBY ON RAILS DEVS who use app/services - this automatically creates the modules and class which is dependant on the file name. put it inside your init.lua file before the return.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- Auto-generate Ruby module/class skeleton for app/services/**.rb | |
| local function camelize(s) | |
| -- foo_bar -> FooBar | |
| return (s:gsub("(%a)([%w_]*)", function(first, rest) | |
| return first:upper() .. rest | |
| end):gsub("_(%a)", function(c) | |
| return c:upper() | |
| end)) | |
| end | |
| local function split_path(p) | |
| local t = {} | |
| for part in p:gmatch("[^/]+") do | |
| table.insert(t, part) | |
| end | |
| return t | |
| end | |
| local function is_empty_buffer(bufnr) | |
| if vim.api.nvim_buf_line_count(bufnr) ~= 1 then return false end | |
| return vim.api.nvim_buf_get_lines(bufnr, 0, 1, false)[1] == "" | |
| end | |
| local function insert_ruby_services_skeleton() | |
| local bufnr = vim.api.nvim_get_current_buf() | |
| if not is_empty_buffer(bufnr) then return end | |
| local fullpath = vim.fn.expand("%:p") | |
| -- match anything after app/services/ and ending in .rb | |
| local rel = fullpath:match("/app/services/(.+)%.rb$") | |
| if not rel then return end | |
| local parts = split_path(rel) | |
| if #parts == 0 then return end | |
| local filename = parts[#parts]:gsub("%.rb$", "") | |
| parts[#parts] = nil | |
| local modules = {} | |
| for _, p in ipairs(parts) do | |
| table.insert(modules, camelize(p)) | |
| end | |
| local class_name = camelize(filename) | |
| local lines = {} | |
| local indent = "" | |
| for _, m in ipairs(modules) do | |
| table.insert(lines, indent .. "module " .. m) | |
| indent = indent .. " " | |
| end | |
| table.insert(lines, indent .. "class " .. class_name) | |
| table.insert(lines, indent .. "end") | |
| for i = #modules, 1, -1 do | |
| indent = indent:sub(1, -3) -- remove two spaces | |
| table.insert(lines, indent .. "end") | |
| end | |
| vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, lines) | |
| local cursor_line = (#modules) + 1 -- line with "class ..." | |
| vim.api.nvim_win_set_cursor(0, { cursor_line + 1, (#modules * 2) }) -- inside class, indentation | |
| end | |
| vim.api.nvim_create_autocmd({ "BufNewFile" }, { | |
| pattern = { "*.rb" }, | |
| callback = insert_ruby_services_skeleton, | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment