Sha256: dd2296b5306e6a36f3a010f09d70a259ce3ce6105f15e62506cd8f508d5840d1

Contents?: true

Size: 1.95 KB

Versions: 5

Compression:

Stored size: 1.95 KB

Contents

# lib/generators/apache_age/scaffold_node/scaffold_node_generator.rb

require 'rails/generators'
require 'rails/generators/named_base'
require 'rails/generators/resource_helpers'

module ApacheAge
  class ScaffoldNodeGenerator < Rails::Generators::NamedBase
    include Rails::Generators::ResourceHelpers

    desc "Generates a node, and its controller and views with the given attributes."
    source_root File.expand_path("templates", __dir__)
    argument :attributes, type: :array, default: [], banner: "field:type field:type"
    class_option :skip_namespace, type: :boolean, default: true, desc: "Skip namespace 'rails_age' in generated files"

    def create_model_file
      invoke 'apache_age:node', [name] + attributes.collect { |attr| "#{attr.name}:#{attr.type}" }
    end

    def create_controller_files
      template(
        "controller.rb.tt",
        File.join(Rails.root, "app/controllers", controller_class_path, "#{controller_file_name}_controller.rb")
      )
    end

    def create_route
      route_content = route_text(class_path, file_name)
      inject_into_file(
        File.join(Rails.root, 'config', 'routes.rb'), "\n#{route_content}",
        after: "Rails.application.routes.draw do"
      )
    end

    def copy_view_files
      available_views.each do |view|
        view_name = view == 'partial' ? "_#{singular_table_name}" : view
        filename = filename_with_extensions(view_name)
        template(
          "views/#{view}.html.erb.tt",
          File.join(Rails.root, "app/views", controller_file_path, filename)
        )
      end
    end

    private

    def available_views
      %w[index edit show new partial _form]
    end

    def filename_with_extensions(view)
      [view, :html, :erb].compact.join('.')
    end

    def route_text(class_path, file_name)
      return "  resources :#{file_name.pluralize}" if class_path.empty?

<<-RUBY
  namespace :#{class_path.join(':')} do
    resources :#{file_name.pluralize}
  end
RUBY
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
rails_age-0.6.4 lib/generators/apache_age/scaffold_node/scaffold_node_generator.rb
rails_age-0.6.3 lib/generators/apache_age/scaffold_node/scaffold_node_generator.rb
rails_age-0.6.2 lib/generators/apache_age/scaffold_node/scaffold_node_generator.rb
rails_age-0.6.1 lib/generators/apache_age/scaffold_node/scaffold_node_generator.rb
rails_age-0.6.0 lib/generators/apache_age/scaffold_node/scaffold_node_generator.rb