My Ruby and Rails cheat sheet

Few things that I find handy when I am working with Ruby on Rails, and ruby in general.

Also contains my go-to resources and few neat things about Ruby

Ruby on Rails

running raw sql from rails(ActiveRecord)

query = "SELECT * from users LIMIT 10"
result = ActiveRecord::Base.connection.execute(query)
# this returns a result set

Ruby Internals and other things

The Kernel module

The Kernel module is included by class Object, so its methods are available in every Ruby object.

It has some nice methods like caller and caller_location, you would use caller and caller_location to know who called a method.

See more:

ObjectSpace

ObjectSpace contains details about all the objects in ruby, it’s used by GC. you can use it get details about objects :)

See more:

GC and GC::Profiler

GC class can be used to interact with Ruby Garbage Collector, and one would use GC::Profiler to see what GC is doing, and get gc stats

See more:

RubyProf

ruby-prof is a profiler for MRI Ruby, it is nice when you are okay with some overhead. I use benchmark-ips to benchmark things.

PS: I wrote a dumb wrapper to profile a part of code, which comes handy.

See more:

NOTE: Try sampling profilers like stackprof or rbspy if you want to profile production code

source_location

We can use source_location to see location(source code) of a method

User.method(:profile_picture).source_location

See more:

RubyVM

RubyVM is spicy, it gives lots of info about Ruby Internals. comes handy when you are debugging something with RubyVM.

Working with this class requires a bit of knowledge of how Interpreters work

The RubyVM module only exists on MRI. RubyVM is not defined in other Ruby implementations such as JRuby and TruffleRuby.

The RubyVM module provides some access to MRI internals. This module is for very limited purposes, such as debugging, prototyping, and research. Normal users must not use it. This module is not portable between Ruby implementations.

as per docs, it comes with disclaimer but I use it to explore things, and get under the hood look

Guides/Docs

I usually refer to official docs or ruby hacking guide when I want to understand something or clear some doubts about things


Continue Reading