Skip to content

Instantly share code, notes, and snippets.

@mrjonesbot
Created January 23, 2020 20:40
Show Gist options
  • Save mrjonesbot/48ddb758302f031a040ae08aadbf4b09 to your computer and use it in GitHub Desktop.
Save mrjonesbot/48ddb758302f031a040ae08aadbf4b09 to your computer and use it in GitHub Desktop.
require 'rails/generators'
class AntennaGenerator < Rails::Generators::NamedBase
source_root File.expand_path('../templates', __FILE__)
argument :actions, type: :array, default: [], banner: "action action"
class_option :skip_routes,
type: :boolean, desc: "Don't add routes to config/routes.rb."
check_class_collision suffix: "Controller"
def add_routes
return if options[:skip_routes]
return if actions.empty?
route generate_routing_code
end
def create_controller_files
template "controller.rb",
File.join("app/controllers", class_path, "#{file_name}_controller.rb")
end
def create_spec_files
template "request_spec.rb",
File.join("spec/requests", class_path, "#{file_name}_spec.rb")
end
private
def remove_possible_suffix(name)
name.sub(/_?controller$/i, "")
end
def generate_routing_code
depth = 0
lines = []
# Create 'namespace' ladder
# namespace :foo do
# namespace :bar do
regular_class_path.each do |ns|
lines << indent("namespace :#{ns} do\n", depth * 2)
depth += 1
end
# Create route
# get 'baz/index'
# get 'baz/show'
joined_actions = actions.join(' ')
lines << "resources :#{file_name}, only: %i[#{joined_actions}]"
# resources :file_name, only: %i[actions.map(&:to_sym).join(' ')]
# actions.each do |action|
# lines << indent(%{get '#{file_name}/#{action}'\n}, depth * 2)
# end
# Create `end` ladder
# end
# end
until depth.zero?
depth -= 1
lines << indent("end\n", depth * 2)
end
lines.join
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment