Skip to content

Instantly share code, notes, and snippets.

@frullah
Last active July 23, 2022 04:56
Show Gist options
  • Save frullah/9f25e6720066d7231fd4dc97beb51ac8 to your computer and use it in GitHub Desktop.
Save frullah/9f25e6720066d7231fd4dc97beb51ac8 to your computer and use it in GitHub Desktop.
Used to create rails app file with module and classes included
#!/usr/bin/env rails runner
#
# Used to create rails app file with module and classes included
#
### How to use
# - Copy this into your bin folder.
# - Make this file executable by using `chmod +x`.
sub_directory = ARGV[0]
constant_name = ARGV[1]
# create file
class RailsFileCreator
attr_reader :sub_directory, :constant_name
INDENT_SIZE = 2
def initialize(sub_directory:, constant_name:)
@sub_directory = sub_directory
@constant_name = constant_name.underscore.camelize
@indent = 0
end
def constant_parts
constant_name.split("::")
end
def module_name_parts
constant_parts[...-1]
end
def class_name
constant_parts[-1]
end
def sub_filepath
# transform constant to filepath (/)
constant_name.underscore
end
def filepath
Rails.root.join("app", sub_directory, sub_filepath).to_s + ".rb"
end
def indent_space
" " * @indent
end
def increment_indent
@indent += INDENT_SIZE
end
def decrement_indent
@indent -= INDENT_SIZE
end
def call
File.open(filepath, "w") do |file|
module_name_parts.each do |module_name_part|
file.write(indent_space)
file.write("module #{module_name_part}")
file.write("\n")
increment_indent
end
file.write(indent_space)
file.write("class #{class_name}")
file.write("\n")
file.write(indent_space)
file.write("end")
file.write("\n")
while @indent.positive?
decrement_indent
file.write(indent_space)
file.write("end")
file.write("\n")
end
end
end
end
RailsFileCreator.new(sub_directory:, constant_name:).call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment