Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this mystery 'j' in Rails?

I was in the rails console, accidentally typed in the letter j and hit enter and it returned nil.

rails c
Loading development environment (Rails 3.2.13)
[6] pry(main)> j
=> nil
[1] pry(main)> j.nil?
=> true

Google didn't get me anywhere. Anybody know what this mysterious j is and what its purpose is? Just curious.

like image 609
Ryan Rebo Avatar asked Dec 16 '15 00:12

Ryan Rebo


Video Answer


1 Answers

You can always found the source of given method using source_location:

method(:j).source_location

Or even its exact definition with pry (or method_source gem):

method(:j).source

Result:

def j(*objs)
  objs.each do |obj|
    puts JSON::generate(obj, :allow_nan => true, :max_nesting => false)
  end
  nil
end

j is a method coming from JSON library (which is adding this method to Kernel module so it is accessible in irb), and it is responsible for displaying given arguments as JSON objects:

j(hello: :world) 
  #=> {"hello":"world"}
  nil

Rails by default require json library so it is available straight away. In pure IRB, you need to require 'json' to have an access to it.

It accepts any number of arguments, so j returns nil without printing anything. It is equivalent of p method, just uses json instead of inspect result.

like image 55
BroiSatse Avatar answered Oct 09 '22 06:10

BroiSatse