diff --git a/README.md b/README.md index 39e083b25..e143a538c 100644 --- a/README.md +++ b/README.md @@ -1042,6 +1042,10 @@ end Of course you are free to extend this as needed and override action handlers or other methods. +A jsonapi-controller generator is avaliable +``` +rails generate jsonapi:controller contact +``` ###### Context diff --git a/lib/generators/jsonapi/USAGE b/lib/generators/jsonapi/USAGE index d1ca0165e..4cebf40e6 100644 --- a/lib/generators/jsonapi/USAGE +++ b/lib/generators/jsonapi/USAGE @@ -1,8 +1,13 @@ Description: Generator for JSONAPI Resources -Example: +Examples: rails generate jsonapi:resource Post This will create: app/resources/post_resource.rb + + rails generate jsonapi:controller Post + + This will create: + app/controllers/posts_controller.rb diff --git a/lib/generators/jsonapi/controller_generator.rb b/lib/generators/jsonapi/controller_generator.rb new file mode 100644 index 000000000..41ee4eb1e --- /dev/null +++ b/lib/generators/jsonapi/controller_generator.rb @@ -0,0 +1,14 @@ +module Jsonapi + class ControllerGenerator < Rails::Generators::NamedBase + source_root File.expand_path('../templates', __FILE__) + + def create_resource + template_file = File.join( + 'app/controllers', + class_path, + "#{file_name.pluralize}_controller.rb" + ) + template 'jsonapi_controller.rb', template_file + end + end +end diff --git a/lib/generators/jsonapi/templates/jsonapi_controller.rb b/lib/generators/jsonapi/templates/jsonapi_controller.rb new file mode 100644 index 000000000..8266f029a --- /dev/null +++ b/lib/generators/jsonapi/templates/jsonapi_controller.rb @@ -0,0 +1,4 @@ +<% module_namespacing do -%> +class <%= class_name.pluralize %>Controller < JSONAPI::ResourceController +end +<% end -%> diff --git a/test/lib/generators/jsonapi/controller_generator_test.rb b/test/lib/generators/jsonapi/controller_generator_test.rb new file mode 100644 index 000000000..faed0637c --- /dev/null +++ b/test/lib/generators/jsonapi/controller_generator_test.rb @@ -0,0 +1,25 @@ +require File.expand_path('../../../../test_helper', __FILE__) +require 'generators/jsonapi/controller_generator' + +module Jsonapi + class ControllerGeneratorTest < Rails::Generators::TestCase + tests ControllerGenerator + destination Rails.root.join('../controllers') + setup :prepare_destination + teardown :cleanup_destination_root + + def cleanup_destination_root + FileUtils.rm_rf destination_root + end + + test "controller is created" do + run_generator ["post"] + assert_file 'app/controllers/posts_controller.rb', /class PostsController < JSONAPI::ResourceController/ + end + + test "controller is created with namespace" do + run_generator ["api/v1/post"] + assert_file 'app/controllers/api/v1/posts_controller.rb', /class Api::V1::PostsController < JSONAPI::ResourceController/ + end + end +end