Skip to content

Instantly share code, notes, and snippets.

@yhk1038
Created May 9, 2021 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yhk1038/5c882fdaf5ee4f26555efd7e36a3b873 to your computer and use it in GitHub Desktop.
Save yhk1038/5c882fdaf5ee4f26555efd7e36a3b873 to your computer and use it in GitHub Desktop.
My own cra-rails template. (It requires permission for a private repository)
require 'json'
def run!
source_dirname = 'create-react-app-with-rails-boilerplate'
client_app_dir = 'client'
git clone: 'https://github.com/yhk1038/create-react-app-with-rails-boilerplate.git'
add_gems
add_gitignore
update_package_json client_dir: client_app_dir
run "cp -r ./#{source_dirname}/client ./#{client_app_dir}"
update_client_package_name client_dir: client_app_dir
run "rm -rf ./#{source_dirname}"
run 'bundle install'
run 'yarn install'
run 'yarn client:install'
end
#######################
def add_gems
gem 'awesome_print'
gem 'dotenv-rails'
end
def add_gitignore
File.open('./.gitignore', 'a') do |f|
f.write <<~CODE
yarn.lock
# Client APP Build Result is run on each production server.
/public/static
/public/asset-manifest.json
/public/manifest.json
/public/index.html
CODE
end
end
# Abstract PackageJson Handler
#
class PackageJson
def initialize(filepath)
@filepath = filepath
end
def read
file = File.read(@filepath)
JSON.parse(file, symbolize_names: true)
end
def write(hash)
File.write(@filepath, "#{JSON.pretty_generate(hash)}\n")
end
def merge!(hash)
data = read
data.merge!(hash)
write data
end
def append
write yield(read)
end
def insert(*before_keys)
append do |hash|
cached_map = before_keys.map do |key|
val = hash[key].dup
hash.delete key
[key, val]
end
yield(hash)
cached_map.each { |key, val| hash[key] = val }
hash
end
end
end
def update_package_json(client_dir: 'client')
package_json = PackageJson.new('./package.json')
package_json.insert(:dependencies, :devDependencies) do |hash|
hash[:scripts] ||= {}
hash[:scripts].merge!(
'client:start': "yarn --cwd #{client_dir} start",
'client:build': "yarn --cwd #{client_dir} build",
'client:install': "yarn --cwd #{client_dir} install"
)
end
end
def update_client_package_name(client_dir: 'client')
package_json = PackageJson.new('./package.json')
rails_app_name = package_json.read[:name]
client_name = "#{rails_app_name}-client"
unless yes?("Update name of 'client' (cra) module? [#{client_name}]")
client_name = ask "What do you want to call the 'client' app?"
end
client_package_json = PackageJson.new("./#{client_dir}/package.json")
client_package_json.merge! name: client_name
end
#######################
run!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment