Skip to main content

Ruby-on-Rails-Tips-and-Tricks

Get source location of a method​

It's very useful to know where (and how) some method is defined, particularly when debugging code or external gems. Given that object is your current Object and method the method that you need information about, his trick can help you:

object.method(:method).source_location

Matching regexp​

When matching regular expressions against a nullable variable always call match (or match?) on the regexp itself in order to avoid NoMethodErrors

[1] pry(main)> value = 'xxx'
"xxx"
[2] pry(main)> value.match?(/some regepx/)
false
[3] pry(main)> /some regexp/.match?(value)
false
[4] pry(main)> value = nil
nil
[5] pry(main)> /some regexp/.match?(value)
false
[6] pry(main)> value.match?(/some regepx/)
NoMethodError: undefined method `match?' for nil:NilClass
from (pry):6:in `<main>'
[7] pry(main)>

Count occurences in an array​

A good syntactic sugar to do that is built-in in Ruby, and it's the Enumerable#tally method

["a", "b", "c", "b"].tally #=> {"a"=>1, "b"=>2, "c"=>1}

Programmatically enable query logging​

Helpful to analyse queries in runtime where the logger is disabled

ActiveRecord::Base.logger = ActiveSupport::Logger.new($stdout)
ActiveRecord::Base.logger.level = Logger::DEBUG
ActiveRecord::Base.verbose_query_logs = true