Skip to content

Instantly share code, notes, and snippets.

@oinak
Created June 17, 2019 21:23
Show Gist options
  • Save oinak/e8ed651e7f7e548817ecd1de45f050a8 to your computer and use it in GitHub Desktop.
Save oinak/e8ed651e7f7e548817ecd1de45f050a8 to your computer and use it in GitHub Desktop.

Rails Boilerplate Script

This is a quick and dirty script to get going with Rails

Assumptions:

  • Docker is installed
  • Docker Compose is installed
  • You will use postgres
  • You want omakase: rails default options (minitest, coffescript, turbolinks, actioncable...)

It expects the rails app/folder name as argument. If missing it will use CWD basename and proceed (beware!)

#!/bin/bash
if [[ ! -z $1 ]]
then
echo "Argument given, create and enter folder"
mkdir -p $1
cd $1
APP_NAME=$1
else
echo "No argument given, asuming current folder"
APP_NAME=$(basename "$PWD")
fi
echo "Generate Dockerfile"
cat << EOF > ./Dockerfile
FROM ruby:2.6
RUN apt-get update -qq && apt-get install -y nodejs postgresql-client
RUN mkdir /myapp
WORKDIR /usr/src/app
COPY Gemfile /usr/src/app/Gemfile
COPY Gemfile.lock /usr/src/app/Gemfile.lock
RUN bundle install
COPY . /usr/src/app
# Add a script to be executed every time the container starts.
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000
# Start the main process.
CMD ["rails", "server", "-b", "0.0.0.0"]
EOF
echo "Generate temporal Gemfile"
cat << EOF > ./Gemfile
source 'https://rubygems.org'
gem 'rails', '~>5'
EOF
echo "Generate temporal Gemfile.lock"
touch Gemfile.lock
echo "Generate entrypoint.sh"
cat << EOF > ./entrypoint.sh
#!/bin/bash
set -e
# Remove a potentially pre-existing server.pid for Rails.
rm -f /myapp/tmp/pids/server.pid
# Then exec the container's main process (what's set as CMD in the Dockerfile).
exec "\$@"
EOF
echo "Generate docker-compese.yml"
cat << EOF > ./docker-compose.yml
version: '3'
services:
db:
image: postgres
app:
build: .
command: bash -c "bundle exec rails s -p 3000 -b '0.0.0.0'"
volumes:
- .:/usr/src/app
ports:
- "3000:3000"
depends_on:
- db
EOF
echo "Build container"
docker-compose build app
echo "Run 'rails new' inside container"
docker-compose run app rails new . --force --no-deps --database=postgresql
echo "Return files to script user"
sudo chown -R $USER .
echo "Rebuild the image to update Gemfile changes"
docker-compose build
echo "Fix config/database.yml"
cat << EOF > config/database.yml
default: &default
adapter: postgresql
encoding: unicode
host: db
username: postgres
password:
pool: 5
development:
<<: *default
database: ${APP_NAME}_development
test:
<<: *default
database: ${APP_NAME}_test
EOF
echo "Create the databases"
docker-compose run --rm app rails db:create
echo "Booting ocker compose cluster"
docker-compose up -d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment