Skip to content

Instantly share code, notes, and snippets.

@ethagnawl
Last active February 21, 2019 01:27
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 ethagnawl/a9a39b52a903f40e84cf7c4248dfbcd2 to your computer and use it in GitHub Desktop.
Save ethagnawl/a9a39b52a903f40e84cf7c4248dfbcd2 to your computer and use it in GitHub Desktop.
Rails 5 (API-only) Notes

The following are some notes I put together while working on a Rails 5 (API-only) application, after having been away from Ruby/Rails for some time. Maybe they'll be useful to others, too?

Testing

  • Inheriting from MiniTest::Unit::TestCase (e.g. class SendOnboardingNotCompleteReminderEmailWorkerTest < MiniTest::Unit::TestCase, as provided by Sidekiq generator) results in: ArgumentError: unknown command 'i'. Use: class SendOnboardingNotCompleteReminderEmailWorkerTest < ActiveSupport::TestCase instead.

  • timecop-like funcionality is baked into ActiveSupport

    include ActiveSupport::Testing::TimeHelpers

    travel_to(1.day.ago) {}

  • FactoryBot values are static unless set using a block: confirmed_at { Time.now }

ActiveRecord

  • enums can be very useful, especially during early iterations/spikes.
  • class with foreign_key uses belongs_to; using has_one will result in "must exist" error
  • has_many :through requires has_many :through_join_table
  • find record which contains an array which contains at least one of a list of arguments
    query = "array[?] && things"    
    things = ["papers", "books"]    
    Stuff.find_by(query, things)

Vim Rails

Vim Rails' intelligent file navigation is very useful and quickly becomes something you wish was available for every language/framework/library. The mnemonics are also very intuitive and once you know them, they'll likely Just Work for models/tests/controllers/etc.

My favorite commands and some notes:

  • :Emigrate edits the latest migration (I was aware of this command but not what the E stood for)
  • :Smigration open the latest migration in a new split
  • :Emodel if executed while editing UsersController will open UserModel

Sidekiq

  • You can't pass kwargs to a Sidekiq worker

Misc

  • I've found the following helper to be very useful for setting required global variables (using ENV vars) from within initializers:
    # lib/helpers.rb
    fetch_from_env_or_fail = lambda { |key|  ENV.fetch(key) { fail "#{key} is required." }}
    
    # config/initializers/redis.rb
    REDIS_HOST = fetch_from_env_or_fail.("REDIS_HOST")
    
  • JSONPlaceholder is very useful for simulating external services
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment