### Project README Template - Setup Instructions Source: https://github.com/rolemodel/bestpractices/blob/master/support/project_readme.md Template for the project setup section, detailing external tool installation, local setup, running tests, and editor plugins. ```bash brew update --system brew upgrade ruby-build git clone http://github.com/RoleModel/ cd rbenv install gem install bundler bundle install ``` ```bash rails s ``` ```bash rake ``` -------------------------------- ### Example Commit Message Source: https://github.com/rolemodel/bestpractices/blob/master/git/commit-messages.md An example demonstrating the commit message template with specific references. ```git Return 404 on permissions API when no access [TR #45] (GH #4) If a user cannot access a study at all we want to be able communicate that to API clients, thus we will return a 404. ``` -------------------------------- ### Install Selenium Server with Homebrew Source: https://github.com/rolemodel/bestpractices/blob/master/testing/selenium_server.md This command installs the Selenium Server package using the Homebrew package manager on macOS/OSX. ```bash $ brew install selenium-server ``` -------------------------------- ### Start Selenium Server Node on Windows VM Source: https://github.com/rolemodel/bestpractices/blob/master/testing/selenium_server.md Starts a Selenium Server node on the Windows virtual machine. This node registers with the hub and specifies the browser and driver configurations. ```bash $ java -jar C:\selenium\selenium-server-standalone-2.53.1.jar -role node -hub http://10.100.1.1:4444/grid/register -maxSession 15 -browser browserName="internet explorer",version=ANY,platform=WINDOWS,maxInstances=5 -Dwebdriver=C:\selenium\IEDriverServer.exe -port 5556 ``` -------------------------------- ### Example Rubocop TODO Configuration Source: https://github.com/rolemodel/bestpractices/blob/master/rails/linter-config.md An example of the .rubocop_todo.yml file generated by `bundle exec rubocop --auto-gen-config`, showing disabled offenses. ```yaml # Offense count: 3 # Configuration parameters: MinBodyLength. Style/GuardClause: Enabled: false # Offense count: 3 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles. # SupportedStyles: line_count_dependent, lambda, literal Style/Lambda: Enabled: false ``` -------------------------------- ### Install ESLint Standalone Source: https://github.com/rolemodel/bestpractices/blob/master/rails/linter-config.md Install ESLint globally using npm for standalone JavaScript linting. ```bash npm install -g eslint ``` -------------------------------- ### Install Rubocop Gem Source: https://github.com/rolemodel/bestpractices/blob/master/rails/linter-config.md Add the rubocop gem to your Gemfile for development and test environments to enable local and CI checks against the Ruby style guide. ```ruby group :development, :test do gem 'rubocop', require: false end ``` -------------------------------- ### Start Selenium Server Hub Source: https://github.com/rolemodel/bestpractices/blob/master/testing/selenium_server.md Initiates the Selenium Server in hub mode. This command should be run on the host machine to manage the testing grid. ```bash $ selenium-server -role hub ``` -------------------------------- ### Example Git Tag Message Source: https://github.com/rolemodel/bestpractices/blob/master/git/tagging-versions.md An example message for an annotated Git tag, including version number, summary, and a sorted list of Trello cards. ```text Version 2.4.1 Hotfix to fix a typo and fix a permission Includes the following cards from the Trello board: - #144 - Correct misspelling of "mispelled" - #145 - Blacklist new spammers ``` -------------------------------- ### Project README Template - Branching Strategy Source: https://github.com/rolemodel/bestpractices/blob/master/support/project_readme.md Instructions for branching strategy, including how to start a new feature branch and requirements for squashing commits before merging. ```git git checkout -b ``` -------------------------------- ### Database Configuration using ENV Variables Source: https://github.com/rolemodel/bestpractices/blob/master/rails/configuration.md This example shows how to use environment variables within `config/database.yml` to manage database connection settings. This allows the `config/database.yml` file to be safely checked into source control. ```yaml default: &default adapter: <%= ENV["DATABASE_ADAPTER"] %> database: <%= ENV["DATABASE_NAME"] %> username: <%= ENV["DATABASE_USER"] %> password: <%= ENV["DATABASE_PASSWORD"] %> pool: <%= ENV["DATABASE_POOL"] %> encoding: <%= ENV["DATABASE_ENCODING"] %> host: <%= ENV["DATABASE_HOST"] %> development: <<: *default test: &test <<: *default database: sample_test production: <<: *default cucumber: <<: *test ``` -------------------------------- ### Setup Standard Git Aliases Source: https://github.com/rolemodel/bestpractices/blob/master/git/setup.md Configure global Git aliases for common commands like status, checkout, and branch to save typing. ```bash git config --global alias.st status git config --global alias.co checkout git config --global alias.br branch ``` -------------------------------- ### Configure GoodJob Queues via Environment Variable Source: https://github.com/rolemodel/bestpractices/blob/master/rails/background_jobs.md Sets up job queues and their concurrency limits using an environment variable. This example configures 'mailers', 'default', and 'pdf' queues with different limits. ```ruby ENV['GOOD_JOB_QUEUES'] = 'mailers:1;default:3;pdf:1;-pdf' ``` -------------------------------- ### Setup Advanced Git Aliases Source: https://github.com/rolemodel/bestpractices/blob/master/git/setup.md Configure global Git aliases for more complex command and argument combinations, such as adding all files or forcing pushes. ```bash git config --global alias.aa 'add --all' git config --global alias.d 'diff --staged' git config --global alias.pf 'push --force-with-lease' git config --global alias.l1 'log --graph --decorate --oneline' git config --global alias.l2 'log --pretty=format:"%C(yellow)%h%Cblue%d%Creset %s %C(white) %an, %ar%Creset" --graph' ``` -------------------------------- ### Start Interactive Rebase Source: https://github.com/rolemodel/bestpractices/blob/master/git/squashing.md Initiates an interactive rebase operation against a specified branch. This command opens an editor to modify the rebase instructions. ```bash git rebase -i release-v12 ``` -------------------------------- ### Example Slack Standup Update Source: https://github.com/rolemodel/bestpractices/blob/master/support/slack_standup.md This is a sample of a daily standup update that includes project details, work location, upcoming time off, and optional sections for gratitude and open-ended discussion. ```text *Today*: Project ABC (production configuration, Background Processing), Lunch w/ Ken @ :home: *OOO*: This Friday, 10/1 - 10/6 *Thankful for:* Son started crawling *OMM:* * LCAD with no react * Which lawn mower brand is best? ``` -------------------------------- ### Search Form with HTTP GET (Good) Source: https://github.com/rolemodel/bestpractices/blob/master/patterns/search.md Use HTTP GET for search forms to allow for discoverable, shareable, and extensible URLs. This is the recommended approach for most search implementations. ```ruby <%= search_form_for @q do |f| %> ``` -------------------------------- ### Install SCSS Lint Gem Source: https://github.com/rolemodel/bestpractices/blob/master/rails/linter-config.md Add the scss_lint gem to your Gemfile for development and test environments to enable SCSS linting. ```ruby group :development, :test do gem 'scss_lint', require: false end ``` -------------------------------- ### Install ESLint Rails Gem Source: https://github.com/rolemodel/bestpractices/blob/master/rails/linter-config.md Add the eslint-rails gem to your Gemfile for development and test environments to integrate ESLint with Rails. ```ruby group :development, :test do gem 'eslint-rails' end ``` -------------------------------- ### Configure GoodJob Queues in Code Source: https://github.com/rolemodel/bestpractices/blob/master/rails/background_jobs.md Defines custom job queues and their priorities directly within the Rails application configuration. This example sets up a 'large_task' queue with a specific priority. ```ruby Rails.application.configure do config.good_job.queues = "large_task:#{max_large_tasks};-large_task" end ``` -------------------------------- ### Heroku App.json for Post-Deploy Database Setup Source: https://github.com/rolemodel/bestpractices/blob/master/rails/database-migrations.md Defines the `postdeploy` script in Heroku's app.json to load the database schema and seed data after deployment. This ensures the database is correctly initialized for review apps. ```json { "name": "Example Heroku Review App", "scripts": { "postdeploy": "bin/rails db:schema:load db:seed" }, } ``` -------------------------------- ### Install Bundler Audit Gem Source: https://github.com/rolemodel/bestpractices/blob/master/rails/linter-config.md Add the bundler-audit gem to your Gemfile for development and test environments to check for security notices in your gems. ```ruby group :development, :test do gem 'bundler-audit' end ``` -------------------------------- ### Get Latest Git Tag Source: https://github.com/rolemodel/bestpractices/blob/master/git/tagging-versions.md Commands to fetch all tag names locally and then list and sort them to find the most recent version number. ```bash git fetch --tags git tag -l | grep '^v' | sort -t. -k1,1n -k2,2n -k3,3n | tail -n1 ``` -------------------------------- ### Linearizable Non-FF Merge Example Source: https://github.com/rolemodel/bestpractices/blob/master/git/merge-strategies.md Demonstrates a linearizable non-fast-forward merge after rebasing the feature branch. This results in a merge commit but maintains a clear, albeit non-linear, commit history. ```git A B C M' o---o---o--------o master \ / F' G' o---o feature ``` -------------------------------- ### Vim Incantation for Squashing Source: https://github.com/rolemodel/bestpractices/blob/master/git/squashing.md A Vim command to quickly change all 'pick' commands to 'squash' starting from the second line, useful for squashing multiple commits. ```vim :2,$s/^pick/squash/ ``` -------------------------------- ### Fast-Forward (FF) Merge Example Source: https://github.com/rolemodel/bestpractices/blob/master/git/merge-strategies.md Shows a fast-forward merge after rebasing the feature branch onto the master branch. This strategy results in a simple linear history with no merge commits, which is recommended for clarity. ```git A B C F' G' o---o---o---o---o master, feature ``` -------------------------------- ### Update main branch with rebase Source: https://github.com/rolemodel/bestpractices/blob/master/git/development-workflow.md Before starting new work, update your local main branch from the remote repository using git rebase. ```git git rebase origin/master ``` -------------------------------- ### Non-linearizable Non-FF Merge Example Source: https://github.com/rolemodel/bestpractices/blob/master/git/merge-strategies.md Illustrates a non-linearizable non-fast-forward merge in Git, resulting in a merge commit with multiple parents. This strategy is generally discouraged due to its complexity in understanding commit history. ```git A B C M o---o---o---o master \ / F G o---o feature ``` -------------------------------- ### Project README Template - Troubleshooting Source: https://github.com/rolemodel/bestpractices/blob/master/support/project_readme.md Template section for troubleshooting, including links to status pages and instructions for checking running services. ```markdown * [App Status Page](http://app..com/_ping) will give you information about what is running. * Alternatively, you can ssh in and check that the application server and web server are both running. ``` -------------------------------- ### Push feature branch and open comparison page Source: https://github.com/rolemodel/bestpractices/blob/master/git/development-workflow.md Switch to your feature branch, push it to the origin remote, and then use the 'hub' command to open a comparison webpage for a pull request. ```git git checkout feature # switch to your feature branch git push -u origin feature # push it to `origin` git compare feature # use the `hub` command to open a comparison webpage ``` -------------------------------- ### Run ESLint on CI to Pass Build Source: https://github.com/rolemodel/bestpractices/blob/master/rails/linter-config.md Run ESLint on CI environments and ensure the build passes regardless of linting errors by using a fallback echo command. ```bash eslint '**/*.js' || echo "Please clean up any errors" ``` -------------------------------- ### Project README Template - Overview Section Source: https://github.com/rolemodel/bestpractices/blob/master/support/project_readme.md Template for the overview section of a README, including project name, purpose, technologies used, and rejected alternatives. ```markdown # Overview ## Name and aliases The project is named "". Some will refer to it as "" or "". ## Purpose The system is designed to solve the problem of ... Users had the problem, but this system resolves it by ... ## Technologies ### Chosen * Ruby on Rails * Postgres * nginx * unicorn ### Tried and rejected * Node.js - Not enough internal experience. * Mongo - Needed to use a relational database for reporting. * Websphere - Cost * webrick - Application servers are using newer technology now. ## Technology relationships ## Supported browsers The customer states that only Chrome will be used. ``` -------------------------------- ### Configure Honeybadger Check-In Mapping Source: https://github.com/rolemodel/bestpractices/blob/master/rails/background_jobs.md Set up the application configuration to map job classes to their respective Honeybadger check-in keys, using environment variables. ```ruby # This expects an environment variable to be defined with a value like this: 'Job1:key1,Job2:key2'. The key values can be acquired when setting up a Honeybadger check-in. config.honeybadger_check_in_config = ENV.fetch('HONEYBADGER_CHECK_IN_CONFIG', '').split(',').to_h { |e| e.split(':') } ``` -------------------------------- ### Run Bundler Audit Source: https://github.com/rolemodel/bestpractices/blob/master/rails/linter-config.md Execute the bundler-audit check command to identify any security vulnerabilities or outdated gems. ```bash bundle-audit check --update ``` -------------------------------- ### Run Full Test Suite Against IE9 Source: https://github.com/rolemodel/bestpractices/blob/master/testing/cross_browser_test.md Execute the entire test suite with the `:javascript` or `@javascript` tags against Internet Explorer 9 using BrowserStack. ```bash bundle exec rake cross_browser:ie9 ``` -------------------------------- ### Rubocop Configuration File Source: https://github.com/rolemodel/bestpractices/blob/master/rails/linter-config.md Create a .rubocop.yml file to configure Rubocop, inheriting from a shared configuration and setting the target Ruby version. ```yaml inherit_from: - https://raw.githubusercontent.com/RoleModel/shared_rubocop/master/.rubocop.yml # This is a minimum Rubocop checks against, not necessarily what is actually # used by the project. AllCops: TargetRubyVersion: 2.2 ``` -------------------------------- ### Interactive Rebase Instructions Source: https://github.com/rolemodel/bestpractices/blob/master/git/squashing.md The content of the editor opened by `git rebase -i`. It lists commits to be replayed and available commands like 'pick', 'reword', 'edit', 'squash', 'fixup', and 'exec'. ```gitconfig pick cab2298 git-ignore more files pick b9f319c Update API version # Rebase 08139c2..b9f319c onto 08139c2 # # Commands: # p, pick = use commit # r, reword = use commit, but edit the commit message # e, edit = use commit, but stop for amending # s, squash = use commit, but meld into previous commit # f, fixup = like "squash", but discard this commit's log message # x, exec = run command (the rest of the line) using shell ``` -------------------------------- ### Run Rubocop Locally or on CI Source: https://github.com/rolemodel/bestpractices/blob/master/rails/linter-config.md Execute Rubocop to check code against style guidelines. This command is used for both local development and CI environments. ```bash bundle exec rubocop ``` -------------------------------- ### Ping Guest Virtual Machine Source: https://github.com/rolemodel/bestpractices/blob/master/testing/selenium_server.md Use the ping command to verify network connectivity between your host machine and the guest virtual machine. This helps in diagnosing network issues. ```bash $ ping 10.100.1.2 ``` -------------------------------- ### Run ESLint Locally (Errors and Warnings) Source: https://github.com/rolemodel/bestpractices/blob/master/rails/linter-config.md Execute ESLint to check JavaScript files for errors and warnings. This command is suitable for local development. ```bash eslint '**/*.js' ``` -------------------------------- ### Run Spinach Scenarios Against IE9 Source: https://github.com/rolemodel/bestpractices/blob/master/testing/cross_browser_test.md Execute Spinach scenarios tagged with `@javascript` against Internet Explorer 9 using BrowserStack. ```bash bundle exec rake cross_browser:spinach:ie9 ``` -------------------------------- ### Ping Host Machine from Guest VM Source: https://github.com/rolemodel/bestpractices/blob/master/testing/selenium_server.md From the Windows VM, ping the host machine's IP address to confirm bidirectional network connectivity. This is crucial for the Selenium Server communication. ```bash $ ping 10.100.1.1 ``` -------------------------------- ### Handle rejected push by fetching and rebasing Source: https://github.com/rolemodel/bestpractices/blob/master/git/development-workflow.md If your push to the release branch is rejected, fetch the latest changes from origin and rebase your local release branch before pushing again. ```git git fetch origin git rebase origin/release git push ``` -------------------------------- ### VS Code Settings for GitHub Copilot Keybindings Source: https://github.com/rolemodel/bestpractices/blob/master/ai_tools/ai_autocomplete.md This JSON configuration for VS Code customizes GitHub Copilot's keybindings. It unbinds the default 'tab' and 'cmd+right' shortcuts, and recommends using ';' to accept full suggestions, 'ctrl+shift+;' for the next line, and 'ctrl+;' for the next word. It also includes a shortcut 'cmd+k cmd+a' to temporarily snooze suggestions. ```javascript [ // Unbind the default shortcut to accept inline suggestions with tab { "key": "tab", "command": "-editor.action.inlineSuggest.commit" }, // Unbind the default "accept next word" shortcut because it interferes with // a common macOS navigation shortcut. { "key": "cmd+right", "command": "-editor.action.inlineSuggest.acceptNextWord", }, // Recommended "accept full suggestion" shortcut. Pick a different key if you // often need to type semicolons. { "key": ";", "command": "editor.action.inlineSuggest.commit", "when": "inlineEditIsVisible || inlineSuggestionVisible" }, // Suggested keyboard shortcuts to accept part of a suggestion { "key": "ctrl+shift+;", "command": "editor.action.inlineSuggest.acceptNextLine" }, { "key": "ctrl+;", "command": "editor.action.inlineSuggest.acceptNextWord", "when": "inlineSuggestionVisible && !editorReadonly" }, // Recommended shortcut to temporarily pause inline completions. // This will prompt to select a duration to snooze suggestions. { "key": "cmd+k cmd+a", "command": "editor.action.inlineSuggest.snooze", "when": "editorFocus", } ] ``` -------------------------------- ### Babel Configuration for ES6 Source: https://github.com/rolemodel/bestpractices/blob/master/rails/es6.md Configure Babel to transpile ES6 code. Add other presets like 'react' as needed. ```json { presets: [ "es2015" ] } ``` -------------------------------- ### Create Annotated Git Tag Source: https://github.com/rolemodel/bestpractices/blob/master/git/tagging-versions.md Command to create an annotated Git tag for a deployment. Use the new version number for the tag name. ```bash git tag -a master ``` -------------------------------- ### Mount GoodJob Engine with Authentication Source: https://github.com/rolemodel/bestpractices/blob/master/rails/background_jobs.md Secure the GoodJob management console by mounting the engine within an authentication block in the routes file, restricting access to administrators. ```ruby authenticate :user, ->(user) { user.admin? } do mount GoodJob::Engine => 'good_job' end ``` -------------------------------- ### Run Specific Spinach File Against IE9 Source: https://github.com/rolemodel/bestpractices/blob/master/testing/cross_browser_test.md Execute Spinach scenarios for a specific feature file tagged with `@javascript` against Internet Explorer 9 using BrowserStack. ```bash bundle exec rake 'cross_browser:spinach:ie9[features/reference_ui/clinical_trials.feature]' ``` -------------------------------- ### Generate Rubocop Auto-Configuration Source: https://github.com/rolemodel/bestpractices/blob/master/rails/linter-config.md Use Rubocop to automatically generate a configuration file (TODO) for current violations, helping to pass builds while listing items to fix. ```bash bundle exec rubocop --auto-gen-config ``` -------------------------------- ### Run All Linters with Rake Source: https://github.com/rolemodel/bestpractices/blob/master/rails/linter-config.md Execute all configured linters using the 'lint' Rake task. This task can be configured to control pass/fail behavior. ```bash bundle exec rake lint ``` -------------------------------- ### Heroku Release Phase Script for Migrations Source: https://github.com/rolemodel/bestpractices/blob/master/rails/database-migrations.md A bash script for Heroku's release phase that conditionally runs `db:migrate` only if the database schema is already set up. It checks the current schema version to prevent migration on a fresh database. ```bash #!/usr/bin/env bash # # Usage: bin/heroku_release set -euo pipefail schema_version=$(bin/rails db:version | { grep "^Current version: [0-9]\+" || true; } | tr -s ' ' | cut -d ' ' -f3) if [ -z "$schema_version" ]; then printf "[Release Phase]: ERROR: Database schema version could not be determined. Does the database exist?\n" exit 1 fi if [ "$schema_version" -ne "0" ]; then printf "\n[Release Phase]: Running db:migrate\n" bin/rails db:migrate else printf "\n[Release Phase]: Skipping db:migrate since database schema is not setup yet.\n" fi ``` -------------------------------- ### Use Resource Policies in Views Source: https://github.com/rolemodel/bestpractices/blob/master/patterns/authorization.md Leverage policies in views to ensure consistent authorization checks for resources. This centralizes logic and simplifies view code. ```slim - if current_user.admin? = render 'accountant' ``` ```slim - if policy(:accountant).show? = render 'accountant' ``` -------------------------------- ### Include env.rb in application.rb Source: https://github.com/rolemodel/bestpractices/blob/master/rails/configuration.md This line should be added to the top of your `application.rb` file to make all configuration values accessible throughout your Rails application. ```ruby require File.expand_path('../../env', __FILE__) ``` -------------------------------- ### Alias Git to Hub Source: https://github.com/rolemodel/bestpractices/blob/master/git/setup.md Configure your shell to use 'hub' as the default git command. This automatically delegates unrecognized commands to git. ```shell alias git='hub' ``` -------------------------------- ### Create and switch to a new feature branch Source: https://github.com/rolemodel/bestpractices/blob/master/git/development-workflow.md Use this command to create a new branch named 'feature' that branches from 'release' and simultaneously switch to the new branch. ```git git checkout -b feature release ``` -------------------------------- ### SSH Access Source: https://github.com/rolemodel/bestpractices/blob/master/support/project_readme.md Standard command to establish an SSH connection to a remote host. Replace 'user' and 'hostname.com' with actual credentials. ```bash ssh user@hostname.com ``` -------------------------------- ### Enable and Define Cron Jobs with GoodJob Source: https://github.com/rolemodel/bestpractices/blob/master/rails/background_jobs.md Configure GoodJob to enable cron job functionality and define scheduled tasks with their cron schedules and associated job classes. ```ruby Rails.application.configure do config.good_job = { enable_cron: true, cron: { pghero_capture_stats: { cron: 'every 5 minutes', class: 'PgHeroCaptureJob' }, pghero_clean_stats: { cron: 'every day at 2am EST', class: 'PgHeroCleanJob' } } } end ``` -------------------------------- ### Heroku Procfile for Release Phase Source: https://github.com/rolemodel/bestpractices/blob/master/rails/database-migrations.md Configures the Heroku Procfile to use a custom script for the release phase, ensuring database migrations are handled correctly during deployments. ```yaml web: bundle exec puma -C config/puma.rb release: bin/heroku_release ``` -------------------------------- ### Continue development and push changes Source: https://github.com/rolemodel/bestpractices/blob/master/git/development-workflow.md After making code changes, add and commit them as usual, then push the changes to your feature branch. ```git # on your `feature` branch # do normal development, including `git add` and `git commit` git push ``` -------------------------------- ### Run ESLint Locally (Errors Only) Source: https://github.com/rolemodel/bestpractices/blob/master/rails/linter-config.md Execute ESLint to check JavaScript files, showing only errors and ignoring warnings. This command helps focus on critical issues. ```bash eslint --quiet '**/*.js' ``` -------------------------------- ### Update UI with Turbo Streams after Job Completion Source: https://github.com/rolemodel/bestpractices/blob/master/rails/background_jobs.md Leverage Turbo::Broadcastable in an after_perform hook to update the user interface with job progress information. ```ruby after_perform do |job| data = job.arguments.first Turbo::StreamsChannel.broadcast_update_to(['my_channel', data.id].join('_'), target: "id-of-div-to-replace", partial: "shared/my_partial", locals: {}) end ``` -------------------------------- ### View Git Log with Graph Source: https://github.com/rolemodel/bestpractices/blob/master/git/squashing.md Displays the commit history with decorations and a graph for visual representation. Useful for understanding the current branch state before squashing. ```bash git log --decorate --oneline --graph ``` -------------------------------- ### Generate Good Job Update Migrations Source: https://github.com/rolemodel/bestpractices/blob/master/rails/background_jobs.md Run this command after updating the Good Job gem to generate necessary migration files for database schema changes. ```ruby bin/rails g good_job:update ``` -------------------------------- ### Configure Server Syslog for Papertrail Source: https://github.com/rolemodel/bestpractices/wiki/Centralized-Logging Add a rule to the rsyslog configuration file on your server to forward all logs to Papertrail. ```bash *.* @SUBDOMAIN.papertrailapp.com:PORT ``` -------------------------------- ### Tagging and Pushing Master Branch Source: https://github.com/rolemodel/bestpractices/blob/master/support/project_readme.md This snippet shows the process for tagging the master branch for deployment and pushing the tags. It assumes the master branch is always deployed to production. ```git git checkout master git tag 2016-05-16 # YYYY-MM-DD git push --tags ``` -------------------------------- ### Run SCSS Lint Locally Source: https://github.com/rolemodel/bestpractices/blob/master/rails/linter-config.md Execute the scss-lint command in your terminal to lint SCSS files in the current directory. ```bash scss-lint ``` -------------------------------- ### NPM Dependencies for ES6 and Babel Source: https://github.com/rolemodel/bestpractices/blob/master/rails/es6.md Include necessary Babel and ES6 related packages in your project's package.json. Ensure versions are compatible. ```json "dependencies": { "babel-core": "^6.14.0", "babel-generator": "^6.14.0", "babel-helpers": "^6.8.0", "babel-polyfill": "^6.7.4", "babel-types": "^6.14.0", "babel-preset-es2015": "^6.9.0", "babel-runtime": "^6.6.1" } ``` -------------------------------- ### Configure Port Forwarding with Netsh Source: https://github.com/rolemodel/bestpractices/blob/master/testing/selenium_server.md This command configures port forwarding on a Windows machine. Ensure you replace the placeholder values with your specific network configuration details. ```bash $ netsh interface portproxy add v4tov4 listenport=3001 listenaddress=localhost connectport=3001 connectaddress=10.100.1.1 ``` -------------------------------- ### Run Individual Linters with Rake Source: https://github.com/rolemodel/bestpractices/blob/master/rails/linter-config.md Execute specific linters individually via Rake tasks. These tasks always return pass/fail exit codes. ```bash bundle exec rake bundle:audit ``` ```bash bundle exec rake rubocop ``` ```bash bundle exec rake scss_lint ``` ```bash bundle exec rake eslint:run ``` -------------------------------- ### Data Migration: Moving Tags to Array Column Source: https://github.com/rolemodel/bestpractices/blob/master/rails/database-migrations.md Migrates data from a separate 'tags' table to an array column in the 'blog_posts' table. Uses `find_each` for memory efficiency with large datasets. Defines local model classes to avoid interference with application models. ```ruby class MoveTags < ActiveRecord::Migration[5.2] # Inherit from ActiveRecord::Base instead of ApplicationRecord since the # ApplicationRecord is subject to changes as the app changes. class Tag < ActiveRecord::Base; end # rubocop:disable Rails/ApplicationRecord class BlogPost < ActiveRecord::Base # rubocop:disable Rails/ApplicationRecord has_many :tags end def up add_column :blog_posts, :categories, :string, array: true say("Moving #{Tag.count} tags to #{BlogPost.count} blog posts") # Use find_each to minimize memory usage when dealing with many records BlogPost.find_each(batch_size: 100) do |blog_post| tags = blog_post.tags.pluck(:value) # You can never have too much logging when migrating data! say("Moving tags #{tags} to BlogPost #{blog_post.id}") blog_post.update!(categories: tags) end end def down remove_column :blog_posts, :categories end end ``` -------------------------------- ### View Tag Message for Version Information Source: https://github.com/rolemodel/bestpractices/blob/master/git/tagging-versions.md Retrieve the message associated with a specific Git tag. This is often used to display customer-visible information, such as release notes or task summaries, for a particular version. ```git git show v1.1 ``` -------------------------------- ### Application JavaScript for React Integration Source: https://github.com/rolemodel/bestpractices/blob/master/rails/es6.md Modify your main JavaScript file to include necessary imports and expose React and ReactDOM globally. Ensure correct order of requires. ```javascript //= require jquery //= require turbolinks //= require react_ujs // require_tree ./components import 'babel-polyfill' import React from "react" import ReactDOM from "react-dom" import DoughnutChart from './components/DoughnutChart' import MyForm from './components/MyForm' window.React = React window.ReactDOM = ReactDOM ``` -------------------------------- ### Enable ActiveJob Performance Monitoring with Skylight Source: https://github.com/rolemodel/bestpractices/blob/master/rails/background_jobs.md Adds an ActiveJob probe to Skylight for monitoring job performance. This configuration should be placed in your application's production.rb initializer. ```ruby config.skylight.probes << 'active_job' ``` -------------------------------- ### Define Honeybadger Check-In Job Source: https://github.com/rolemodel/bestpractices/blob/master/rails/background_jobs.md Create a job responsible for performing the Honeybadger check-in, retrieving the necessary key from application configuration. ```ruby class CheckInJob < ApplicationJob def perform(source_job_id:, source_job_class:) key = Rails.application.config.honeybadger_check_in_config[source_job_class] raise 'Check-in failed' unless Honeybadger.check_in(key) end end ``` -------------------------------- ### Configure Job Retries and Discards Source: https://github.com/rolemodel/bestpractices/blob/master/rails/background_jobs.md Set up automatic retries for transient errors and discard jobs that fail due to specific issues like deserialization errors or record not found. ```ruby ActiveJob::Base.retry_on StandardError, wait: :polynomially_longer, attempts: 25 # Automatically retry jobs that encountered a deadlock ActiveJob::Base.retry_on ActiveRecord::Deadlocked ActiveJob::Base.discard_on ActiveJob::DeserializationError ActiveJob::Base.discard_on ActiveRecord::RecordNotFound ``` -------------------------------- ### Run RSpec Scenarios Against IE9 Source: https://github.com/rolemodel/bestpractices/blob/master/testing/cross_browser_test.md Execute RSpec scenarios tagged with `:javascript` against Internet Explorer 9 via BrowserStack. ```bash bundle exec rake cross_browser:rspec:ie9 ``` -------------------------------- ### Checkout and Rebase Feature Branch Source: https://github.com/rolemodel/bestpractices/blob/master/git/release-branching.md Use this command to rebase a feature branch onto a specific point in the release branch. Ensure 'F^' refers to the commit before the first unique commit on your feature branch. ```git git checkout feature git rebase --onto release F^ ``` -------------------------------- ### Configure Rails Production/Staging Logger for Papertrail Source: https://github.com/rolemodel/bestpractices/blob/master/devops/centralized_logging.md Set up the logger in Rails production and staging environments to send logs to Papertrail using the RemoteSyslogLogger. ```ruby config.logger = RemoteSyslogLogger.new('SUBDOMAIN.papertrailapp.com', PORT, program: "rails-#{Rails.application.class.name.split('::').first}") config.logger.level = Logger::Severity::INFO ``` -------------------------------- ### Ignore Rubocop's Local Config Copy Source: https://github.com/rolemodel/bestpractices/blob/master/rails/linter-config.md Add a rule to .gitignore to prevent Rubocop's locally downloaded shared configuration file from being committed. ```bash # Ignore Rubocop's local copy of our shared Rubocop config .rubocop-https* ``` -------------------------------- ### Search Form with HTTP POST (Bad) Source: https://github.com/rolemodel/bestpractices/blob/master/patterns/search.md Avoid using HTTP POST for search forms as it hinders discoverability and shareability. This snippet demonstrates the incorrect approach. ```ruby <%= search_form_for @q, html: { method: :post } do |f| %> ``` -------------------------------- ### Configure Rails Application Logging Source: https://github.com/rolemodel/bestpractices/wiki/Centralized-Logging Set up RemoteSyslogLogger for Rails applications in the production environment to send logs to Papertrail. ```ruby config.logger = RemoteSyslogLogger.new(‘SUBDOMAIN.papertrailapp.com', PORT, program: "rails-#{Rails.application.class.name.split('::').first}") config.logger.level = Logger::Severity::INFO ``` -------------------------------- ### Update Gemfile for Good Job v2 to v3 Migration Source: https://github.com/rolemodel/bestpractices/blob/master/rails/background_jobs.md Temporarily update the Gemfile to a .99 version to ensure backward compatibility during a major version upgrade of Good Job. ```ruby gem 'good_job', '~>2.99' ``` -------------------------------- ### List Commits Between Two Versions Source: https://github.com/rolemodel/bestpractices/blob/master/git/tagging-versions.md Use this command to view all Git commits that fall between two specified version tags. This is useful for tracking changes introduced in a specific release. ```git git log v1.0..v1.1 ``` ```git git log --oneline v1.0..v1.1 ``` ```git git diff v1.0..v1.1 ``` -------------------------------- ### Honeybadger Total Job Failure Chart Query Source: https://github.com/rolemodel/bestpractices/blob/master/rails/background_jobs.md SQL query for Honeybadger to track the total count of failed jobs per hour in the production environment. Requires Honeybadger version 5.7.0+. ```sql fields @ts, context.job_class::str, context.action::str, environment::str | filter context.action == "perform" | filter environment::str == 'production' | stats count() as failed_job_count by bin(1h) ``` -------------------------------- ### Update Gemfile for Good Job v1 to v2 Migration Source: https://github.com/rolemodel/bestpractices/blob/master/rails/background_jobs.md Temporarily update the Gemfile to a .99 version to ensure backward compatibility during a major version upgrade of Good Job. ```ruby gem 'good_job', '~>1.99' ``` -------------------------------- ### Set up Error Reporting Callback for ActiveJob Source: https://github.com/rolemodel/bestpractices/blob/master/rails/background_jobs.md This callback intercepts job execution to catch and report errors using a service like Honeybadger before re-raising them. Ensure your Honeybadger gem version is 5.7.0 or later for full integration. ```ruby ActiveJob::Base.set_callback(:perform, :around) do |param, block| begin block.call rescue StandardError => e # notify error service # re-raise the error raise e end end ``` -------------------------------- ### Run Specific RSpec File Against IE9 Source: https://github.com/rolemodel/bestpractices/blob/master/testing/cross_browser_test.md Execute RSpec scenarios for a particular file tagged with `:javascript` against Internet Explorer 9 through BrowserStack. ```bash bundle exec rake 'cross_browser:rspec:ie9[spec/features/support/release_notes_spec.rb]' ``` -------------------------------- ### Run Rubocop with Fail Level Source: https://github.com/rolemodel/bestpractices/blob/master/rails/linter-config.md Configure Rubocop to exit with a failing error code only for ERROR severity offenses or higher, useful for CI environments. ```bash bundle exec rubocop --fail-level ERROR ``` -------------------------------- ### Clean Up Old Jobs Source: https://github.com/rolemodel/bestpractices/blob/master/rails/background_jobs.md Use this command to clean up preserved job records older than a specified duration. This is a crucial step before major version upgrades of Good Job. ```ruby bundle exec good_job cleanup_preserved_jobs --before-seconds-ago=1209600 ``` -------------------------------- ### Enable Job Preservation in Good Job Source: https://github.com/rolemodel/bestpractices/blob/master/rails/background_jobs.md Configure Good Job to preserve job records by setting `GoodJob.preserve_job_records` to true in the initializer. This is required for certain upgrade paths. ```ruby GoodJob.preserve_job_records = true ``` -------------------------------- ### Default Environment Variables in env.rb Source: https://github.com/rolemodel/bestpractices/blob/master/rails/configuration.md This snippet defines default environment variables for Rails configuration, including database settings and API credentials. It ensures safe values are checked into source control. ```ruby # Local override dotenv = File.expand_path("../.env_overrides.rb", __FILE__) require dotenv if File.exist?(dotenv) ENV["RAILS_ENV"] ||= "development" ENV["DATABASE_ADAPTER"] ||= "postgresql" ENV["DATABASE_NAME"] ||= "griefnet_#{ENV["RAILS_ENV"]}" ENV["DATABASE_USER"] ||= "root" ENV["DATABASE_PASSWORD"] ||= "" ENV["DATABASE_ENCODING"] ||= "utf8" ENV["DATABASE_HOST"] ||= "localhost" ENV["DATABASE_POOL"] ||= "5" ENV["POSTGRES_INTERACTIVE"] ||= "psql" ENV["DEVELOPMENT_PORT"] ||= "7100" ENV["MANDRILL_USERNAME"] ||= "" ENV["MANDRILL_PASSWORD"] ||= "" ``` -------------------------------- ### Extract Authorization Logic to Policy Source: https://github.com/rolemodel/bestpractices/blob/master/patterns/authorization.md Move authorization checks from controllers into dedicated policy objects. This improves code organization and maintainability. ```ruby class PostsController < ApplicationController def destroy post = Post.find(params[:id]) if post.user_id == current_user.id post.destroy redirect_to posts_path else redirect_to posts_path, alert: 'Forbidden' end end end ``` ```ruby class PostPolicy < ApplicationPolicy def destroy? record.user_id == user.id end end class PostsController < ApplicationController def destroy post = authorize Post.find(params[:id]) if post.destroy redirect_to posts_path else redirect_to posts_path, alert: 'Forbidden' end end end ``` -------------------------------- ### Rename Good Job Reperform Jobs Configuration Source: https://github.com/rolemodel/bestpractices/blob/master/rails/background_jobs.md Rename the `GoodJob.reperform_jobs_on_standard_error` configuration option to `GoodJob.retry_on_unhandled_error` if necessary, as part of Good Job version upgrades. ```ruby GoodJob.reperform_jobs_on_standard_error ``` ```ruby GoodJob.retry_on_unhandled_error ``` -------------------------------- ### Rails Asset Pipeline Manifest Source: https://github.com/rolemodel/bestpractices/blob/master/rails/es6.md Configure the asset pipeline manifest file to link Sprockets to your JavaScript and CSS assets. ```javascript //= link_tree ../images //= link_directory ../javascripts .js //= link_directory ../stylesheets .css ``` -------------------------------- ### Shell Alias for Git Status Source: https://github.com/rolemodel/bestpractices/blob/master/git/setup.md Create a shell alias for the 'git status' command for quicker access. Options include a short format. ```bash alias gs="git status" # or alias s="git status" # or for shorter terminal output alias gs="git status -sb" ``` -------------------------------- ### Add Heroku Drain for Papertrail Source: https://github.com/rolemodel/bestpractices/wiki/Centralized-Logging Configure your Heroku application to send logs to Papertrail by adding a syslog drain. ```bash heroku drains:add syslog://SUBDOMAIN.papertrailapp.com:PORT ``` -------------------------------- ### Honeybadger Job Failure by Job Type Query Source: https://github.com/rolemodel/bestpractices/blob/master/rails/background_jobs.md SQL query for Honeybadger to count job failures per day, broken down by job class in the production environment. Requires Honeybadger version 5.7.0+. ```sql fields @ts, @preview, message::str, context.job_class::str, context.action::str, environment::str | filter context.action::str == 'perform' | filter environment::str == 'production' | stats count(), context.job_class::str by bin(1d), context.job_class::str ``` -------------------------------- ### Implement Check-In Concern for Job Success Source: https://github.com/rolemodel/bestpractices/blob/master/rails/background_jobs.md Define a concern that triggers a Honeybadger check-in after a job successfully completes, using the job's ID and class. ```ruby module CheckIn extend ActiveSupport::Concern included do after_perform do |job| CheckInJob.perform_later(source_job_id: job.job_id.to_s, source_job_class: job.class.to_s) end end end ``` -------------------------------- ### React Component Rendering in Rails Views Source: https://github.com/rolemodel/bestpractices/blob/master/rails/es6.md Use the react_component helper method provided by the react-rails gem to render React components within your Rails views. ```ruby = react_component('ScorecardsDoughnutChart', graph_data) ``` -------------------------------- ### Commit Message Template Source: https://github.com/rolemodel/bestpractices/blob/master/git/commit-messages.md Use this template for structuring commit messages, including references to task management and source control. ```git [<board abbreviation> #<card number>] (<source control abbreviation> #<pull request number>) <highlights of feature change if any> ``` -------------------------------- ### Rakefile Configuration for Test Environment Source: https://github.com/rolemodel/bestpractices/blob/master/rails/configuration.md This snippet modifies the Rakefile to set the `RAILS_ENV` to 'test' before running Rake tasks like `rake spec`. This ensures tests run with the correct environment configuration. ```ruby # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require File.expand_path('../config/application', __FILE__) Sample::Application.load_tasks task :test_environment do ENV['RAILS_ENV'] = 'test' end task :spec => [:test_environment] ``` -------------------------------- ### Re-checkout Release Branch Source: https://github.com/rolemodel/bestpractices/blob/master/git/release-branching.md An alternative method for team members to reset their local release branches to the remote version. ```git git branch -D release git fetch git checkout release ```