rails_react_scaffold 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +7 -0
  3. data/CODE_OF_CONDUCT.md +84 -0
  4. data/Gemfile +8 -0
  5. data/LICENSE.txt +21 -0
  6. data/README.md +75 -0
  7. data/Rakefile +4 -0
  8. data/lib/generators/rails_react_scaffold/controller_generator.rb +53 -0
  9. data/lib/generators/rails_react_scaffold/generator_helpers.rb +95 -0
  10. data/lib/generators/rails_react_scaffold/templates/controller.rb +76 -0
  11. data/lib/generators/rails_react_scaffold/templates/react_components/edit_page.js.erb +23 -0
  12. data/lib/generators/rails_react_scaffold/templates/react_components/form.js.erb +130 -0
  13. data/lib/generators/rails_react_scaffold/templates/react_components/index_page.js.erb +121 -0
  14. data/lib/generators/rails_react_scaffold/templates/react_components/new_page.js.erb +22 -0
  15. data/lib/generators/rails_react_scaffold/templates/react_components/show_page.js.erb +74 -0
  16. data/lib/generators/rails_react_scaffold/templates/views/edit.html.erb +7 -0
  17. data/lib/generators/rails_react_scaffold/templates/views/index.html.erb +7 -0
  18. data/lib/generators/rails_react_scaffold/templates/views/index.json.jbuilder +1 -0
  19. data/lib/generators/rails_react_scaffold/templates/views/index.json.rabl +11 -0
  20. data/lib/generators/rails_react_scaffold/templates/views/new.html.erb +7 -0
  21. data/lib/generators/rails_react_scaffold/templates/views/show.html.erb +7 -0
  22. data/lib/generators/rails_react_scaffold/templates/views/show.json.jbuilder +1 -0
  23. data/lib/generators/rails_react_scaffold/templates/views/show.json.rabl +11 -0
  24. data/lib/rails_react_scaffold/version.rb +5 -0
  25. data/lib/rails_react_scaffold.rb +8 -0
  26. data/sig/rails_react_scaffold.rbs +4 -0
  27. metadata +72 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 18b1352090b47f7482237fffaef270b990c9d7d754c0da2e205430c54edd5541
4
+ data.tar.gz: 44131cc992121147161ec94c2e9a958ad6bd25a896eb1482c93baa8fc61659d9
5
+ SHA512:
6
+ metadata.gz: bdd59ca44d2e9d4f63eddde9194608961d4fd194c15e7bd0a87d4705ae7442a11fd05abdab4af62c68c328985a4da75ca5cc199de046f54e1676d9a16b88f712
7
+ data.tar.gz: 27351ace6f4d03668a1821844441a4aac877f8dd3412d218339a2b11a13ffc0087e2d91f67065e998896ee6523795b3c1de7550ee397654e3929f87c0926415d
data/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-02-17
4
+
5
+ - Initial release
6
+ - Support for jQuery and Fetch AJAX engines
7
+ - Support for RABL JSON engine
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at casey.li@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in rails_react_scaffold.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Casey Li
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,75 @@
1
+ # Rails React Scaffold
2
+
3
+ This gem will allow you create scaffold for Ruby on Rails applications that use React as their front end. It basically overrides the default Views in the rails scaffold generator to generate a mount point HTML file and an associated React component for all the default Rails views (index, show, new, edit).
4
+
5
+ **Note: This gem is in its early days of development and right now only supports generating the views. Thus you have to have an existing model to use this. In the future, we will program an entire scaffold generator.**
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'rails_react_scaffold'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install rails_react_scaffold
22
+
23
+ ## Usage
24
+
25
+ At this point, this generator only generates VIEWS and assumes a model is in place. So at this point, use the standard model generator that comes pre-built with Rails or code your own model, then use this generator.
26
+
27
+ ### Basic Usage
28
+
29
+ #### Step 1
30
+
31
+ Generate your Rails model however you want.
32
+
33
+ #### Step 2
34
+
35
+ ```
36
+ rails g rails_react_scaffold:controller MODEL_NAME
37
+ ```
38
+
39
+ ### Options
40
+
41
+ |Option|Type|Description|Default|
42
+ |------|----|-----------|-------|
43
+ |`component_dir`|string|The directory where the generated components will be placed|`app/javascript/components`|
44
+ |`component_ext`|string|The file extension to use for generated react components. (js, jsx)|`js`|
45
+ |`ajax_engine`|string|What you want to use to make your Ajax calls (fetch, jQuery, axios) **axios coming soon**|`fetch`|
46
+ |`json_engine`|string|What to use to generate your JSON responses (jbuiler, rabl) **jbuilder coming soon**|`jbuilder`|
47
+ |`use_cancan`|boolean|If you want to load and authorize resources through CanCan(Can).|`false`|
48
+ |`use_remount`|boolean|**Coming soon** If you want to use Remount to mount your components.|`false`|
49
+ |`use_webpacker`|boolean|If you want to use javascript_pack_tag to include your JS in your ERB files.|`false`|
50
+ |`use_webpacker_chunks`|boolean|If you want use javascript_packs_with_chunks_tag to include your JS in your ERB files.|`false`|
51
+
52
+
53
+ ### Example Usage
54
+
55
+ ```
56
+ rails g rails_react_scaffold:controller Book --component_dir app/javascript/src --use_cancan --ajax_engine jquery --use_webpacker_chunks
57
+ ```
58
+
59
+ ## Development
60
+
61
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
62
+
63
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
64
+
65
+ ## Contributing
66
+
67
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/rails_react_scaffold. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/rails_react_scaffold/blob/main/CODE_OF_CONDUCT.md).
68
+
69
+ ## License
70
+
71
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
72
+
73
+ ## Code of Conduct
74
+
75
+ Everyone interacting in the RailsReactScaffold project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/rails_react_scaffold/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ task default: %i[]
@@ -0,0 +1,53 @@
1
+ require 'generators/rails_react_scaffold/generator_helpers'
2
+
3
+ module RailsReactScaffold
4
+ module Generators
5
+ # Custom scaffolding generator
6
+ class ControllerGenerator < Rails::Generators::NamedBase
7
+ include Rails::Generators::ResourceHelpers
8
+ include RailsReactScaffold::Generators::GeneratorHelpers
9
+
10
+ source_root File.expand_path('../templates', __FILE__)
11
+
12
+ desc "Generates views for the model with the given NAME."
13
+
14
+ class_option :component_dir, type: :string, default: "app/javascript/components", desc: "Specify components directory"
15
+ class_option :component_ext, type: :string, default: "js", desc: "Extension to use for generated React components. (e.g. js vs jsx)"
16
+ class_option :ajax_engine, type: :string, default: "fetch", desc: "What you wan to use for your Ajax calls (fetch, jquery, axios)"
17
+ class_option :json_engine, type: :string, default: "jbuilder", desc: "What you would like to use to render your JSON (jbuilder, rabl)"
18
+ class_option :use_remount, type: :boolean, default: false, desc: "Use Remount for mounting components"
19
+ class_option :use_webpacker, type: :boolean, default: false, desc: "Use Webpacker for JS Bundling"
20
+ class_option :use_webpacker_chunks, type: :boolean, default: false, desc: "Use chunks with Webpacker for JS Bundling"
21
+ class_option :use_cancan, type: :boolean, default: false, desc: "Use CanCan(Can) to load and authorize resources"
22
+
23
+ def add_routes
24
+ routes_string = "resources :#{plural_name}"
25
+ route routes_string
26
+ end
27
+
28
+ def copy_controller_and_spec_files
29
+ template "controller.rb", File.join("app/controllers", "#{controller_file_name}_controller.rb")
30
+ end
31
+
32
+ def copy_view_files
33
+ views_directory_path = File.join("app/views", controller_file_path)
34
+ react_components_directory_path = File.join(options['component_dir'], controller_file_path)
35
+ empty_directory views_directory_path
36
+
37
+ view_files.each do |file_name|
38
+ template "views/#{file_name}.html.erb", File.join(views_directory_path, "#{file_name}.html.erb")
39
+ end
40
+
41
+ json_files.each do |file_name|
42
+ template "views/#{file_name}.json.#{options[:json_engine]}", File.join(views_directory_path, "#{file_name}.json.#{options[:json_engine]}")
43
+ end
44
+
45
+ component_files.each do |suffix|
46
+ extension = options[:component_ext]
47
+ template "react_components/#{suffix}.js.erb", File.join(react_components_directory_path, "#{plural_name}_#{suffix}.#{extension}")
48
+ end
49
+ end
50
+
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,95 @@
1
+ module RailsReactScaffold
2
+ module Generators
3
+ # Some helpers for generating scaffolding
4
+ module GeneratorHelpers
5
+ attr_accessor :options, :viewable_attributes, :editable_attributes
6
+
7
+ private
8
+
9
+ # def show_action?
10
+ # !options['skip_show']
11
+ # end
12
+
13
+ def model_exists?
14
+ File.exist?("#{Rails.root}/app/models/#{singular_name}.rb")
15
+ end
16
+
17
+ def model_columns_for_viewable_attributes
18
+ class_name.constantize.columns
19
+ end
20
+
21
+ def viewable_attributes
22
+ viewable_attributes ||= if model_exists?
23
+ model_columns_for_viewable_attributes.map do |column|
24
+ Rails::Generators::GeneratedAttribute.new(column.name.to_s, column.type.to_s)
25
+ end
26
+ else
27
+ []
28
+ end
29
+ end
30
+
31
+ def model_columns_for_editable_attributes
32
+ class_name.constantize.columns.reject do |column|
33
+ column.name.to_s =~ /^(id|created_at|updated_at)$/
34
+ end
35
+ end
36
+
37
+
38
+ def editable_attributes
39
+ editable_attributes ||= if model_exists?
40
+ model_columns_for_editable_attributes.map do |column|
41
+ Rails::Generators::GeneratedAttribute.new(column.name.to_s, column.type.to_s)
42
+ end
43
+ else
44
+ []
45
+ end
46
+ end
47
+
48
+ # def field_to_check_update
49
+ # @field_update_in_spec ||= if text_field = editable_attributes.find { |attr| attr.type == 'string' }
50
+ # { name: text_field.name, old_value: "'Just Text'", new_value: "'New Text'" }
51
+ # elsif numeric_field = editable_attributes.find { |attr| attr.type == 'integer' }
52
+ # { name: numeric_field.name, old_value: 1, new_value: 2 }
53
+ # else
54
+ # false
55
+ # end
56
+ # end
57
+
58
+ # def all_actions
59
+ # actions = %w(index new create edit update destroy)
60
+ # actions << 'show' if show_action?
61
+ # actions
62
+ # end
63
+
64
+ def view_files
65
+ actions = %w(index show new edit)
66
+ actions
67
+ end
68
+
69
+ def json_files
70
+ actions = %w(index show)
71
+ actions
72
+ end
73
+
74
+ def component_files
75
+ suffixes = %w(index_page show_page new_page edit_page form)
76
+ suffixes
77
+ end
78
+
79
+
80
+ # def controller_methods(dir_name)
81
+ # all_actions.map do |action|
82
+ # read_template("#{dir_name}/#{action}.rb")
83
+ # end.join("\n").strip
84
+ # end
85
+
86
+ # def source_path(relative_path)
87
+ # File.expand_path(File.join("../templates/", relative_path), __FILE__)
88
+ # end
89
+
90
+ # def read_template(relative_path)
91
+ # ERB.new(File.read(source_path(relative_path)), nil, '-').result(binding)
92
+ # end
93
+ end
94
+ end
95
+ end
@@ -0,0 +1,76 @@
1
+ class <%= controller_class_name %>Controller < ApplicationController
2
+ <%- if options[:use_cancan] -%>
3
+ load_and_authorize_resource
4
+ <%- else -%>
5
+ before_action :set_<%= singular_name %>, only: [:show, :edit, :destroy]
6
+ <%- end -%>
7
+
8
+ def index
9
+ <%- if !options[:use_cancan] -%>
10
+ @<%= plural_name %> = <%= class_name %>.all
11
+
12
+ <%- end -%>
13
+ respond_to do |format|
14
+ format.html
15
+ format.json
16
+ end
17
+ end
18
+
19
+ def show
20
+ respond_to do |format|
21
+ format.html
22
+ format.json
23
+ end
24
+ end
25
+
26
+ def new
27
+ end
28
+
29
+ def create
30
+ <%- if !options[:use_cancan] -%>
31
+ @<%= singular_name %> = <%= class_name %>.new(<%= singular_name %>_params)
32
+
33
+ <%- end -%>
34
+ respond_to do |format|
35
+ if @<%= singular_name %>.save
36
+ format.json { render :show, status: :created, location: @<%= singular_name %> }
37
+ else
38
+ format.json { render json: @<%= singular_name %>.errors, status: :unprocessable_entity }
39
+ end
40
+ end
41
+ end
42
+
43
+ def edit
44
+
45
+ end
46
+
47
+ def update
48
+ respond_to do |format|
49
+ if @<%= singular_name %>.update(<%= singular_name %>_params)
50
+ format.json { render :show, status: :ok, location: @<%= singular_name %> }
51
+ else
52
+ format.json { render json: @<%= singular_name %>.errors, status: :unprocessable_entity }
53
+ end
54
+ end
55
+ end
56
+
57
+ def destroy
58
+ @<%= singular_name %>.destroy
59
+
60
+ respond_to do |format|
61
+ format.json { head :no_content }
62
+ end
63
+ end
64
+
65
+ private
66
+
67
+ <%- if !options[:use_cancan] -%>
68
+ def set_<%= singular_name %>
69
+ @<%= singular_name %> = <%= class_name %>.find params[:id]
70
+ end
71
+ <%- end -%>
72
+
73
+ def <%= singular_name %>_params
74
+ params.require(:<%= singular_name %>).permit(<%= editable_attributes.map{|attribute| ":#{attribute.name}"}.join(", ") %>)
75
+ end
76
+ end
@@ -0,0 +1,23 @@
1
+ import React from 'react';
2
+ import ReactDOM from 'react-dom';
3
+ import <%= plural_name.camelize %>Form from './<%= plural_name %>_form';
4
+
5
+ const <%= plural_name.camelize %>EditPage = ({ <%= singular_name.camelize(:lower)%>Id }) => (
6
+ <div>
7
+ <h1>Editing <%= singular_name %> {<%= singular_name.camelize(:lower)%>Id}</h1>
8
+ <<%= plural_name.camelize %>Form <%= singular_name.camelize(:lower) %>Id={<%= singular_name.camelize(:lower)%>Id} />
9
+ </div>
10
+ );
11
+
12
+ <% if options['use_remount'] %>
13
+ /* REMOUNT COMING SOON */
14
+ <% else %>
15
+ document.addEventListener('DOMContentLoaded', () => {
16
+ const mountPoint = document.getElementById('<%= "#{plural_name}-edit-page-mount-point" %>');
17
+
18
+ if(mountPoint) {
19
+ const <%= singular_name %>Id = parseInt(mountPoint.dataset.<%= singular_name.camelize(:lower) %>Id);
20
+ ReactDOM.render(<<%= "#{plural_name.camelize}EditPage" %> <%= singular_name %>Id={<%= singular_name %>Id} />, mountPoint);
21
+ }
22
+ });
23
+ <% end %>
@@ -0,0 +1,130 @@
1
+ import React from 'react';
2
+ import { useState, useEffect } from 'react';
3
+
4
+ const <%= plural_name.camelize %>Form = ({ <%= singular_name.camelize(:lower)%>Id }) => {
5
+
6
+ const [loading, setLoading] = useState(true);
7
+ const [submitting, setSubmitting] = useState(false);
8
+ <%- editable_attributes.each do |attribute| -%>
9
+ const [<%= attribute.name.camelize(:lower) %>, <%= "set#{attribute.name.camelize}" %>] = useState();
10
+ <%- end -%>
11
+
12
+ const load<%= singular_name.camelize %> = () => {
13
+ if (<%= singular_name.camelize(:lower)%>Id) {
14
+ const url = `/<%= plural_name %>/${<%= singular_name.camelize(:lower)%>Id}`;
15
+
16
+ <%- if options[:ajax_engine] == 'fetch' -%>
17
+ fetch(url, { headers: { Accept: 'application/json' } })
18
+ .then((response) => {
19
+ if (response.status === 200) {
20
+ return response.json();
21
+ }
22
+ return undefined;
23
+ })
24
+ .then((responseJson) => {
25
+ if (responseJson) {
26
+ <%- editable_attributes.each do |attribute| -%>
27
+ <%= "set#{attribute.name.camelize}" %>(responseJson.<%= attribute.name %>);
28
+ <%- end -%>
29
+ }
30
+ setLoading(false);
31
+ });
32
+ <%- end -%>
33
+ <%- if options[:ajax_engine] == 'jquery' -%>
34
+ $.getJSON(url, (result) => {
35
+ <%- editable_attributes.each do |attribute| -%>
36
+ <%= "set#{attribute.name.camelize}" %>(result.<%= attribute.name %>);
37
+ <%- end -%>
38
+ setLoading(false);
39
+ });
40
+ <%- end -%>
41
+ <%- if options[:ajax_engine] == 'axios' -%>
42
+ /* Axios coming soon */
43
+ <%- end -%>
44
+ } else {
45
+ setLoading(false);
46
+ }
47
+ }
48
+
49
+ const handleSubmit = () => {
50
+ setSubmitting(true);
51
+
52
+ let method = 'POST';
53
+ let url = '/<%= plural_name %>';
54
+ let redirectUrl = '/<%= plural_name%>';
55
+ const data = {
56
+ <%= singular_name %>: {
57
+ <%- editable_attributes.each do |attribute| -%>
58
+ <%= attribute.name %>: <%= attribute.name.camelize(:lower) %>,
59
+ <%- end -%>
60
+ }
61
+ };
62
+
63
+ if (<%= singular_name.camelize(:lower)%>Id) {
64
+ method = 'PUT';
65
+ url = `/<%= plural_name %>/${<%= singular_name.camelize(:lower)%>Id}`;
66
+ redirectUrl = `/<%= plural_name %>/${<%= singular_name.camelize(:lower)%>Id}`;
67
+ }
68
+
69
+ <%- if options[:ajax_engine] == 'fetch' -%>
70
+ const csrfToken = document.querySelector("[name='csrf-token']").content;
71
+
72
+ fetch(url, {
73
+ method,
74
+ headers: {
75
+ 'Content-Type': 'application/json',
76
+ Accept: 'application/json',
77
+ 'X-CSRF-Token': csrfToken,
78
+ },
79
+ body: JSON.stringify(data),
80
+ }).then((response) => {
81
+ if (response.status === 200 || response.status === 201) {
82
+ window.location.href = redirectUrl;
83
+ }
84
+ });
85
+ <%- end -%>
86
+ <%- if options[:ajax_engine] == 'jquery' -%>
87
+
88
+ $.ajax({
89
+ url,
90
+ method,
91
+ data,
92
+ dataType: 'JSON',
93
+ success: () => {
94
+ window.location.href = redirectUrl;
95
+ },
96
+ error: () => {}
97
+ });
98
+ <%- end -%>
99
+ <%- if options[:ajax_engine] == 'axios' -%>
100
+ /* Axios coming soon */
101
+ <%- end -%>
102
+ };
103
+
104
+ useEffect(() => {
105
+ load<%= singular_name.camelize %>();
106
+ }, []);
107
+
108
+ return (
109
+ <div>
110
+ {
111
+ loading ?
112
+ "Loading.."
113
+ :
114
+ <>
115
+ <%- editable_attributes.each do |attribute| -%>
116
+ <div className="field">
117
+ <label><%= attribute.name.titleize %></label>
118
+ <input type="text" value={<%= attribute.name.camelize(:lower) %>} onChange={(e) => set<%= attribute.name.camelize %>(e.target.value)} />
119
+ </div>
120
+ <%- end -%>
121
+ <div className="actions">
122
+ <input type="submit" value={submitting ? 'Submitting...' : 'Submit'} onClick={handleSubmit} />
123
+ </div>
124
+ </>
125
+ }
126
+ </div>
127
+ );
128
+ };
129
+
130
+ export default <%= plural_name.camelize %>Form;
@@ -0,0 +1,121 @@
1
+ import React from 'react';
2
+ import { useState, useEffect } from 'react';
3
+ import ReactDOM from 'react-dom';
4
+
5
+ const <%= plural_name.camelize %>IndexPage = () => {
6
+
7
+ const [loading, setLoading] = useState(false);
8
+ const [<%= plural_name.camelize(:lower) %>, set<%= plural_name.camelize %>] = useState([]);
9
+
10
+ const load<%= plural_name.camelize%> = () => {
11
+ setLoading(true);
12
+ const url = '/<%= plural_name %>';
13
+ <%- if options[:ajax_engine] == 'fetch' -%>
14
+ fetch(url, { headers: { Accept: 'application/json' } })
15
+ .then((response) => {
16
+ if (response.status === 200) {
17
+ return response.json();
18
+ }
19
+ return undefined;
20
+ })
21
+ .then((responseJson) => {
22
+ if (responseJson) {
23
+ set<%= plural_name.camelize %>(responseJson);
24
+ }
25
+ setLoading(false);
26
+ });
27
+ <%- end -%>
28
+ <%- if options[:ajax_engine] == 'jquery' %>
29
+ $.getJSON(url, (results) => {
30
+ set<%= plural_name.camelize %>(results);
31
+ setLoading(false);
32
+ });
33
+ <%- end -%>
34
+ <%- if options[:ajax_engine] == 'axios' -%>
35
+ /* Axios coming soon */
36
+ <%- end -%>
37
+ };
38
+
39
+ const destroy = (<%= singular_name.camelize(:lower) %>Id) => {
40
+ if (window.confirm('Are you sure?')) {
41
+ <%- if options[:ajax_engine] == 'fetch' -%>
42
+ const csrfToken = document.querySelector("[name='csrf-token']").content;
43
+
44
+ fetch(`/<%= plural_name %>/${<%= singular_name.camelize(:lower) %>Id}`, { method: 'DELETE', headers: { Accept: 'application/json', 'X-CSRF-Token': csrfToken } }).then((response) => {
45
+ if (response.status === 204) {
46
+ load<%= plural_name.camelize%>();
47
+ }
48
+ });
49
+ <%- end -%>
50
+ <%- if options[:ajax_engine] == 'jquery' -%>
51
+ $.ajax({
52
+ url: `/<%= plural_name %>/${<%= singular_name.camelize(:lower) %>Id}`,
53
+ method: 'DELETE',
54
+ success: () => {
55
+ load<%= plural_name.camelize%>();
56
+ },
57
+ error: () => {},
58
+ });
59
+ <%- end -%>
60
+ <%- if options[:ajax_engine] == 'axios' -%>
61
+ /* Axios coming soon */
62
+ <%- end -%>
63
+ }
64
+ }
65
+
66
+ useEffect(() => {
67
+ load<%= plural_name.camelize%>();
68
+ }, []);
69
+
70
+ return (
71
+ <div>
72
+ <h1><%= plural_name.titleize %></h1>
73
+
74
+ <div>
75
+ <a href='/<%= plural_name %>/new'>New <%= singular_name %></a>
76
+ </div>
77
+ {
78
+ loading ?
79
+ "Loading..."
80
+ :
81
+ <table>
82
+ <thead>
83
+ <tr><% viewable_attributes.each do |viewable_attribute| %>
84
+ <th><%= viewable_attribute.name.titleize%></th><% end %>
85
+ <th></th>
86
+ <th></th>
87
+ <th></th>
88
+ </tr>
89
+ </thead>
90
+ <tbody>
91
+ {
92
+ <%= plural_name.camelize(:lower) %>.map((<%= singular_name.camelize(:lower) %>) =>
93
+ (
94
+ <tr key={<%= singular_name.camelize(:lower) %>.id}><% viewable_attributes.each do |viewable_attribute| %>
95
+ <td>{<%= "#{singular_name.camelize(:lower)}.#{viewable_attribute.name}" %>}</td><% end %>
96
+ <td><a href={`/<%= plural_name %>/${<%= singular_name.camelize(:lower) %>.id}`}>Show</a></td>
97
+ <td><a href={`/<%= plural_name %>/${<%= singular_name.camelize(:lower) %>.id}/edit`}>Edit</a></td>
98
+ <td><a href='#' onClick={(e) => { e.preventDefault(); destroy(<%= singular_name.camelize(:lower) %>.id); }}>Destroy</a></td>
99
+ </tr>
100
+ )
101
+ )
102
+ }
103
+ </tbody>
104
+ </table>
105
+ }
106
+
107
+ </div>
108
+ );
109
+ };
110
+
111
+ <%- if options['use_remount'] -%>
112
+ /* REMOUNT COMING SOON */
113
+ <%- else -%>
114
+ document.addEventListener('DOMContentLoaded', () => {
115
+ const mountPoint = document.getElementById('<%= "#{plural_name}-index-page-mount-point" %>');
116
+
117
+ if(mountPoint) {
118
+ ReactDOM.render(<<%= "#{plural_name.camelize}IndexPage" %> />, mountPoint);
119
+ }
120
+ });
121
+ <%- end -%>
@@ -0,0 +1,22 @@
1
+ import React from 'react';
2
+ import ReactDOM from 'react-dom';
3
+ import <%= plural_name.camelize %>Form from './<%= plural_name %>_form';
4
+
5
+ const <%= plural_name.camelize %>NewPage = () => (
6
+ <div>
7
+ <h1>New <%= singular_name %></h1>
8
+ <<%= plural_name.camelize %>Form />
9
+ </div>
10
+ );
11
+
12
+ <%- if options['use_remount'] -%>
13
+ /* REMOUNT COMING SOON */
14
+ <%- else -%>
15
+ document.addEventListener('DOMContentLoaded', () => {
16
+ const mountPoint = document.getElementById('<%= "#{plural_name}-new-page-mount-point" %>');
17
+
18
+ if(mountPoint) {
19
+ ReactDOM.render(<<%= "#{plural_name.camelize}NewPage" %> />, mountPoint);
20
+ }
21
+ });
22
+ <%- end -%>
@@ -0,0 +1,74 @@
1
+ import React, { useState, useEffect } from 'react';
2
+ import ReactDOM from 'react-dom';
3
+ const <%= plural_name.camelize %>ShowPage = ({ <%= singular_name.camelize(:lower)%>Id }) => {
4
+
5
+ const [loading, setLoading] = useState(true);
6
+ const [<%= singular_name.camelize(:lower) %>, set<%= singular_name.camelize %>] = useState();
7
+
8
+ const load<%= singular_name.camelize %> = () => {
9
+ setLoading(true);
10
+ const url = `/<%= plural_name %>/${<%= singular_name.camelize(:lower)%>Id}`;
11
+ <%- if options[:ajax_engine] == 'fetch' -%>
12
+ fetch(url, { headers: { Accept: 'application/json' } })
13
+ .then((response) => {
14
+ if (response.status === 200) {
15
+ return response.json();
16
+ }
17
+ return undefined;
18
+ })
19
+ .then((responseJson) => {
20
+ if (responseJson) {
21
+ set<%= singular_name.camelize %>(responseJson);
22
+ }
23
+ setLoading(false);
24
+ });
25
+ <%- end -%>
26
+ <%- if options[:ajax_engine] == 'jquery' -%>
27
+ $.getJSON(url, (result) => {
28
+ set<%= singular_name.camelize %>(result);
29
+ setLoading(false);
30
+ });
31
+ <%- end -%>
32
+ <%- if options[:ajax_engine] == 'axios' -%>
33
+ /* Axios coming soon */
34
+ <%- end -%>
35
+ };
36
+
37
+ useEffect(() => {
38
+ load<%= singular_name.camelize %>();
39
+ }, []);
40
+
41
+ return (
42
+ <div>
43
+ <h1><%= singular_name.titleize %> {<%= singular_name.camelize(:lower)%>Id}</h1>
44
+ {
45
+ loading ?
46
+ "Loading..."
47
+ :
48
+ <>
49
+ <%- viewable_attributes.each do |viewable_attribute| -%>
50
+ <p>
51
+ <b><%= viewable_attribute.name.titleize %></b>: {<%= "#{singular_name.camelize(:lower)}.#{viewable_attribute.name}" %>}
52
+ </p>
53
+ <%- end -%>
54
+ </>
55
+ }
56
+ <div>
57
+ <a href="/<%= plural_name %>">Back to <%= plural_name %></a>
58
+ </div>
59
+ </div>
60
+ );
61
+ };
62
+
63
+ <%- if options['use_remount'] -%>
64
+ /* REMOUNT COMING SOON */
65
+ <%- else -%>
66
+ document.addEventListener('DOMContentLoaded', () => {
67
+ const mountPoint = document.getElementById('<%= "#{plural_name}-show-page-mount-point" %>');
68
+
69
+ if(mountPoint) {
70
+ const <%= singular_name %>Id = parseInt(mountPoint.dataset.<%= singular_name.camelize(:lower) %>Id);
71
+ ReactDOM.render(<<%= "#{plural_name.camelize}ShowPage" %> <%= singular_name %>Id={<%= singular_name %>Id} />, mountPoint);
72
+ }
73
+ });
74
+ <%- end -%>
@@ -0,0 +1,7 @@
1
+ <%- if options[:use_webpacker_chunks] -%>
2
+ <%= "<%= javascript_packs_with_chunks_tag '#{plural_name}/#{plural_name}_edit_page' %%>" %>
3
+ <%- end -%>
4
+ <%- if options[:use_webpacker] -%>
5
+ <%= "<%= javascript_pack_tag '#{plural_name}/#{plural_name}_edit_page' %%>" %>
6
+ <%- end -%>
7
+ <div id="<%= "#{plural_name}-edit-page-mount-point" %>" data-<%= singular_name.dasherize %>-id=<%= "<%= @#{singular_name}.id %%>" %>></div>
@@ -0,0 +1,7 @@
1
+ <%- if options[:use_webpacker_chunks] -%>
2
+ <%= "<%= javascript_packs_with_chunks_tag '#{plural_name}/#{plural_name}_index_page' %%>" %>
3
+ <%- end -%>
4
+ <%- if options[:use_webpacker] -%>
5
+ <%= "<%= javascript_pack_tag '#{plural_name}/#{plural_name}_index_page' %%>" %>
6
+ <%- end -%>
7
+ <div id="<%= "#{plural_name}-index-page-mount-point" %>"></div>
@@ -0,0 +1 @@
1
+ # JBuilder Coming Soon
@@ -0,0 +1,11 @@
1
+ collection @<%= plural_name %>
2
+
3
+ <%- viewable_attributes.each_with_index do |attribute, index| -%>
4
+ <%- if index == 0 -%>
5
+ attributes :<%= attribute.name -%>,
6
+ <%- elsif index == (viewable_attributes.size - 1) -%>
7
+ :<%= attribute.name %>
8
+ <%- else -%>
9
+ :<%= attribute.name %>,
10
+ <%- end -%>
11
+ <%- end -%>
@@ -0,0 +1,7 @@
1
+ <%- if options[:use_webpacker_chunks] -%>
2
+ <%= "<%= javascript_packs_with_chunks_tag '#{plural_name}/#{plural_name}_new_page' %%>" %>
3
+ <%- end -%>
4
+ <%- if options[:use_webpacker] -%>
5
+ <%= "<%= javascript_pack_tag '#{plural_name}/#{plural_name}_new_page' %%>" %>
6
+ <%- end -%>
7
+ <div id="<%= "#{plural_name}-new-page-mount-point" %>"></div>
@@ -0,0 +1,7 @@
1
+ <%- if options[:use_webpacker_chunks] -%>
2
+ <%= "<%= javascript_packs_with_chunks_tag '#{plural_name}/#{plural_name}_show_page' %%>" %>
3
+ <%- end -%>
4
+ <%- if options[:use_webpacker] -%>
5
+ <%= "<%= javascript_pack_tag '#{plural_name}/#{plural_name}_show_page' %%>" %>
6
+ <%- end -%>
7
+ <div id="<%= "#{plural_name}-show-page-mount-point" %>" data-<%= singular_name.dasherize %>-id=<%= "<%= @#{singular_name}.id %%>" %>></div>
@@ -0,0 +1 @@
1
+ # JBuilder Coming Soon
@@ -0,0 +1,11 @@
1
+ object @<%= singular_name %>
2
+
3
+ <%- viewable_attributes.each_with_index do |attribute, index| -%>
4
+ <%- if index == 0 -%>
5
+ attributes :<%= attribute.name %>,
6
+ <%- elsif index == (viewable_attributes.size - 1) -%>
7
+ :<%= attribute.name %>
8
+ <%- else -%>
9
+ :<%= attribute.name %>,
10
+ <%- end -%>
11
+ <%- end %>
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RailsReactScaffold
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "rails_react_scaffold/version"
4
+
5
+ module RailsReactScaffold
6
+ class Error < StandardError; end
7
+ # Your code goes here...
8
+ end
@@ -0,0 +1,4 @@
1
+ module RailsReactScaffold
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,72 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rails_react_scaffold
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Casey Li
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-02-19 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: This gem overrides the default scaffold generators to build scaffolds
14
+ that use React views.
15
+ email:
16
+ - casey.li@gmail.com
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - CHANGELOG.md
22
+ - CODE_OF_CONDUCT.md
23
+ - Gemfile
24
+ - LICENSE.txt
25
+ - README.md
26
+ - Rakefile
27
+ - lib/generators/rails_react_scaffold/controller_generator.rb
28
+ - lib/generators/rails_react_scaffold/generator_helpers.rb
29
+ - lib/generators/rails_react_scaffold/templates/controller.rb
30
+ - lib/generators/rails_react_scaffold/templates/react_components/edit_page.js.erb
31
+ - lib/generators/rails_react_scaffold/templates/react_components/form.js.erb
32
+ - lib/generators/rails_react_scaffold/templates/react_components/index_page.js.erb
33
+ - lib/generators/rails_react_scaffold/templates/react_components/new_page.js.erb
34
+ - lib/generators/rails_react_scaffold/templates/react_components/show_page.js.erb
35
+ - lib/generators/rails_react_scaffold/templates/views/edit.html.erb
36
+ - lib/generators/rails_react_scaffold/templates/views/index.html.erb
37
+ - lib/generators/rails_react_scaffold/templates/views/index.json.jbuilder
38
+ - lib/generators/rails_react_scaffold/templates/views/index.json.rabl
39
+ - lib/generators/rails_react_scaffold/templates/views/new.html.erb
40
+ - lib/generators/rails_react_scaffold/templates/views/show.html.erb
41
+ - lib/generators/rails_react_scaffold/templates/views/show.json.jbuilder
42
+ - lib/generators/rails_react_scaffold/templates/views/show.json.rabl
43
+ - lib/rails_react_scaffold.rb
44
+ - lib/rails_react_scaffold/version.rb
45
+ - sig/rails_react_scaffold.rbs
46
+ homepage: https://github.com/bitesite/rails_react_scaffold
47
+ licenses:
48
+ - MIT
49
+ metadata:
50
+ homepage_uri: https://github.com/bitesite/rails_react_scaffold
51
+ source_code_uri: https://github.com/bitesite/rails_react_scaffold
52
+ changelog_uri: https://github.com/bitesite/rails_react_scaffold/blob/master/CHANGELOG.md
53
+ post_install_message:
54
+ rdoc_options: []
55
+ require_paths:
56
+ - lib
57
+ required_ruby_version: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: 2.6.0
62
+ required_rubygems_version: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: '0'
67
+ requirements: []
68
+ rubygems_version: 3.3.7
69
+ signing_key:
70
+ specification_version: 4
71
+ summary: Gem to build Rails scaffolds for Rails projects that use React front ends.
72
+ test_files: []