Skip to content

Ruby & Rails

alex [dot] kramer [at] g_m_a_i_l [dot] com edited this page Dec 2, 2024 · 13 revisions

Upgrade rbenv ruby version

brew update && brew upgrade ruby-build && rbenv install 3.1.2 && rbenv global 3.1.2

Private module methods

module M
  def self.pub
    puts "pub!"
	self.priv
  end
  
  def self.priv
    puts "priv!"
  end
  
  class << self
    private :priv
  end
end

Rails

Run code after rails starts

config.after_initialize do
  puts "SOME_VAR: #{ENV.fetch('SOME_VAR')}"
end

Clear ActiveJob queue

Delayed::Job.destroy_all

ActiveRecord Queries

# Get all Things sorted by creation time
latest_things = Thing.where(some_column: "some value").sort_by(&:created_at)

# Get set of possible values of field not equal to "whatever"
Thing.where.not(muh_field: 'whatever').pluck(:muh_field).to_set

Check and run migrations

rails db:migrate:status
bundle exec rails db:migrate

Rspec

Capybara (browser based test scenarios; ruby)
                  │
                  ▼
Selenium ruby API (ruby API that maps to Selenese,
the Selenium browser-automation scripting language)
                  │
                  ▼
Driver (e.g. Chromedriver; browser-specific bindings
for executing Selenese scripts against a particular browser)

List specs in order they would be run for a given seed

bundle exec rspec --dry-run --seed 12345 -f json | jq -r '.examples[].file_path' | uniq

Test ActiveJob retry_on

class MyJob < ApplicationJob
  @@foo = 0
  def perform()
    @@foo += 1
    puts("TRYING... #{@@foo}")
    raise "LOLFAIL #{@@foo}"
  end

  retry_on StandardError, attempts: 5, wait: 1 do |job, error|
    FooService.foo
    puts("FAIL... #{@@foo}: #{error}")
  end
end

class FooService
  def self.foo
  end
end

RSpec.describe MyJob, type: :model do
  include ActiveJob::TestHelper

  describe "#perform" do
    it "performs job 5 times and finally calls foo" do
      expect(FooService).to receive(:foo)

      assert_performed_jobs 5 do
        MyJob.perform_later rescue nil
      end
    end
  end
end

Mock controller module method

module FooModule
  extend ActiveSupport::Concern
  
  private
  
  def foo
    "FOO!"
  end
end

class FooController < ActionController::API
  include FooModule

  def index
    render json: { key: foo }, status: 666
  end
end

feature 'Foo', type: :request do
  scenario "foo" do
    allow_any_instance_of(FooController).to receive(:foo).and_return("BAR!")
  
    get "/foo"
    expect(response).to have_http_status(666)
    expect(response.body).to eq('{"key":"BAR!"}')
  end
end

Screenshot during test

timestamp = DateTime.now.strftime("%Y%m%d%H%M%S")
page.save_screenshot("/tmp/rspec_screenshots/screenshot.#{timestamp}.png", full: true)

Gems

HTTParty

Turn on debug logging:

response = HTTParty.post(
  "https://tw.yahoo.com",
  headers: headers,
  body: body.to_json,
  debug_output: $stdout
)

Wavefile

https://wavefilegem.com/

Generate descending saw tone

require "wavefile"
include WaveFile

SAMPLE_RATE = 44100
FORMAT = Format.new(:mono, :float, SAMPLE_RATE)

def square(lambda, vol, duration_ms)
  num_cycles = (duration_ms/1000.0) * (SAMPLE_RATE / lambda)
  ([vol] * (lambda/2) + [-vol] * (lambda/2)) * num_cycles
end

Writer.new("/tmp/descending.wav", Format.new(:mono, :pcm_16, SAMPLE_RATE)) do |writer|
  for lambda in (1..1000)
    writer.write(Buffer.new(square(lambda, 0.1, 100), FORMAT))
  end
end
Clone this wiki locally