Skip to content

Instantly share code, notes, and snippets.

@Dav1s-Ops
Forked from cjsim89/b3_rails_cheatsheet.md
Last active September 3, 2023 16:25
Show Gist options
  • Save Dav1s-Ops/3dd953a32369b3e67b26ea45c8c2f1d6 to your computer and use it in GitHub Desktop.
Save Dav1s-Ops/3dd953a32369b3e67b26ea45c8c2f1d6 to your computer and use it in GitHub Desktop.
B3 Rails Cheatsheet

B3 Rails Cheatsheet

Rails Encrypted Credentials

First step, run this command:

EDITOR="code --wait" rails credentials:edit

When we run this command, a new key is created in config/master.key as well as a credentials temp file thats opened in your text editor (in this case VSCode denoted by EDITOR="code --wait").

Then simply add your key in a similar format as the propublica example below:

propublica:
  key: asdsa3498serghjirteg978ertertwhter

# Used as the base secret for all MessageVerifiers in Rails, including the one protecting cookies.
secret_key_base: ugsdfeadsfg98a7sd987asjkas98asd87asdkdwfdg876fgd

This will all use to use Rails.application.credentials.<your header>[:<your key>] syntax to replace:

faraday.headers["X-API-Key"] = ENV["PROPUBLICA_API_KEY"]

With this:

faraday.headers["X-API-Key"] = Rails.application.credentials.propublica[:key]

This works anywhere you may be using a conn variable to request from an endpoint. Here is the line once more:

Rails.application.credentials.propublica[:key]

Just remember to replace propublica with the key and [:key] with your API key as the value. It's data type appears to be a hash with a key/value pair.

Faraday

Getting a basic response:

  response = Faraday.get({url})

Re-use your connection to the same API, while handling different endpoints:

  conn = Faraday.new({base url})
  
  response1 = conn.get("/api/v1/thing/1")
  data = JSON.parse(response1.body)
  
  response2 = conn.post("api/v1/other-thing", {name: 'John', age: '30'})
  data2 = JSON.parse(response2.body)

Postman

  • Docs
  • Used as a specialized browser for making HTTP requests, organizable by collection.

Testing APIs

  • When consuming an API, it is best to mock the request so that we can save on HTTP requests to different services. This is because some API providers will limit the # of requests to their endpoints in total, or per hour/day.
  • Lesson

Webmock

  1. Make sure webmock is installed in the Gemfile's :test group. Run bundle install.
  2. Add require 'webmock/rspec' to spec_helper.rb file
  3. Add the stub_request and .to_return methods to your test. Ex:
stub_request(:method, "the API endpoint")
.to_return(status: ###, body: ..., headers: {#optional}) 

Optionally, add a fixture file andFile.read it into your test. You can use Postman to get the raw data. When you run your test, Webmock will give you helpful error messages with the code to add. Usually (though not always) you can copy-paste that code and remove the headers info.

VCR

  • Docs
  • Use VCR to automatically store fixture files inside of named "cassettes".
  • Configuration-heavy, but can configure per-block or per-test suite.
  1. Add gem "vcr" to our :test block in Gemfile, run bundle.
  2. Add this codeblock to rails_helper.rb:
# VCR configuration
VCR.configure do |config|
  config.cassette_library_dir = 'spec/fixtures/vcr_cassettes'
  config.hook_into :webmock
  config.filter_sensitive_data('<hidden_key>') { Rails.application.credentials.<your header>[:<your key>] }
  config.default_cassette_options = { record: :new_episodes }
  config.configure_rspec_metadata!
end
  1. Add either a :vcr flag to a test, or set up VCR.use_cassette('name') to tests that you'll want to use VCR fixture data for.
  • If using the :vcr flag per-test, add following to config block:
config.configure_rspec_metadata!
  1. If you are using API keys as part of your requests, remember to put config.filter_sensitive_data in the VCR configuration in rails_helper. NOTE - filter_sensitive_data takes two params: first is what it will turn the second into. Example:
config.filter_sensitive_data("<hidden_key>") { Rails.application.credentials.<your header>[:<your key>] }
  • VCR cassettes can expire, where manual fixture files have to be manually deleted. You can do per-cassette expiration, or global in the config block. Per-cassettes will override the global configuration.
# Per-cassette expiration: 

VCR.use_cassette('name_of_cassette', re_record_interval: 7.days) do 
   # test code goes here 
end

# Globally, in VCR config block:

config.default_cassette_options = { re_record_interval: 7.days }

FactoryBot & Faker

In your Gemfile:

group :development, :test do
  gem "factory_bot_rails"
  gem "faker"
end

Using RSpec

In your spec/rails_helper.rb add to the RSpec.configure block

 config.include FactoryBot::Syntax::Methods

The following line should currently be commented out in rails_helper.rb. Find it and uncomment it. This line will allow us to require all ruby files that we put inside of the spec/support directory.

Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }

Option 1 (Manual):

  1. Create a directory for our configuration of FactoryBot mkdir spec/support
  2. Add a factory_bot.rb file. touch spec/support/factory_bot.rb

Option 2 (Scaffolding):

  1. Run a Model-generated migration like the one in the example below:
rails g model Book title author genre summary:text number_sold:integer
  1. This should generate all necessary directories and files related to the model including the Factory (as long as FactoryBot was configured already)! EZ

Refactoring

Building APIs in Rails

Customizing JSON - Serialization

Error Handling

Basic Authentication

Sessions, Cookies, Authorization

Service-Oriented Architecture (microservices)

Writing good READMEs

Background Workers

Caching

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment