We sometimes have to read library codes for curiosity or bug fixes. However, there are some techniques needed, so I’ll write them down here.

Set up path for installing gems

bundle config set path ‘vendor/bundle’ —- local

Codes of library become visible in our projects and it has become possible to insert pry codes into libraries.

Find where methods are defined

class Book
def read
end
end
> Book.new.method(:read).source_location
=> ['book.rb', 2]

Use debuggers

・binding.irb

・binding.pry

・byebug

Find a caller

・puts caller

class BooksController < ApplicationController
def index
puts caller
end
end
# caller is default in Ruby

・backtrace(this is in byebug)

That’s all! Make debugging more effective by using techniques above.

My LinkedIn account is below! Please contact me!

https://www.linkedin.com/in/tomoharu-tsutsumi-56051a126/

An incident happened that our application in a production environment didn’t read environment variables. OS is Ubuntu and the deploy tool we use is capistrano.

At first, though I wrote environment variables in .bash_profile, they weren’t read. However, when I logged in a production server with ssh and checked them out, they were read.

The reason is below.

“By default Capistrano always assigns a non-login, non-interactive shell.”

Thus, .bash_profile is not read in capistrano by default.

I wrote environment variables in ~etc/environment of Ubuntu in order to iron out the issue and it worked!

My LinkedIn account is below! Please contact me!

https://www.linkedin.com/in/tomoharu-tsutsumi-56051a126/

Suppose we develop mailer functions and want to test it, what should we do?

Useful way

The answer is below. The code is following the library above.

RSpec.describe 'test', type: :request do
include ActiveJob::TestHelper

context 'test1' do
def call
# ....some mailer functions
end
it 'send an email' do
expect { call }.to have_enqueued_job.on_queue('mailers')
expect(enqueued_jobs.size).to eq 1
end
end
end

have_enqueued_job returns…

[{:id=>"xxxxxxxxxxxxxxxx", :job=>ActionMailer::DeliveryJob, :args=>["Mailer", "method", "deliver_now", {"_aj_globalid"=>"gid://product/class/:id"}], :queue=>"mailers"}]

My LinkedIn account is below! Please contact me!

https://www.linkedin.com/in/tomoharu-tsutsumi-56051a126/

When I faced this problem, I spent 3~4 hours solving it. I’ll summarize it in order not to forget it again.

My original code

User.transaction do   
user = User.create!(param)
UserMailWorker.perform_async(user.id)
end

It is a pity that this code sometimes doesn’t work because UserMailWorker is executed before transaction is committed. Thus, there is no user when Worker is executed. This issue is mentioned in Sidekiq.

Solution

It is very simple.

User.transaction do   
user = User.create!(param)
end
UserMailWorker.perform_async(user.id)

This code will work rightly!

My LinkedIn account is below! Please contact me!

https://www.linkedin.com/in/tomoharu-tsutsumi-56051a126/