require "rails/generators" module QuestionsCrafter module Generators class QuestionsGenerator < Rails::Generators::NamedBase source_root File.expand_path("templates", __dir__) argument :questions, type: :array, default: [], desc: "List of questions in format name:type (types: short, long, boolean, choice)" def create_questions_file @parsed_questions = parse_questions(questions) template "questions.rb.erb", "app/questions/#{file_path}.rb" end # Both class_name and file_path were overriden to add the "Questions" suffix if needed similar to how Rails does it for controllers def class_name intermediate_class_name = super intermediate_class_name.match(/Questions$/) ? intermediate_class_name : "#{intermediate_class_name}Questions" end def file_path path = super path.match(/questions$/) ? path : "#{path}_questions" end private def parse_questions(questions_array) questions_array.map do |question_def| name, type = question_def.split(":") type = "string" if type.nil? || type.empty? case type.downcase when "string" { name: name, type: "string", title: name.humanize } when "text" { name: name, type: "text", title: name.humanize } when "boolean" { name: name, type: "boolean", title: name.humanize } when "radio" { name: name, type: "radio", title: name.humanize, has_options: true } when "integer" { name: name, type: "integer", title: name.humanize } when "select" { name: name, type: "select", title: name.humanize, has_options: true } when "checkbox_group" { name: name, type: "checkbox_group", title: name.humanize, has_options: true } else { name: name, type: "string", title: name.humanize } end end end end end end