Tuesday, January 12, 2016

How to find out if a name is reserved in Rails 4.2.5

One of the articles that gets lot of traffic is : Reserved Words in Rails. If you do not use the generator to generate the code in your Rails project, you could potentially have class collision during runtime of your application. Here are the steps I followed:

1. I browsed the railties gem and searched for 'reserved by Ruby on Rails' to find where in the source code the check is done.
2. It is defined in the class rails/generators/base.rb in class_collisions(*class_names) protected method.
3. I went to the rails console to figure out how to use this method:

> require 'rails/generators/base'
NameError: uninitialized constant Rails::Generators::Actions
from /Users/bparanj/.rvm/gems/railties-4.2.5/lib/rails/generators/base.rb:17:in `'
pry(main)> require 'rails/generators/actions'
=> true
 pry(main)> require 'rails/generators/base'
=> true
 pry(main)> g = Rails::Generators::Base.new
=> # @_initializer=[[], {}, {}],
 @_invocations={},
 @after_bundle_callbacks=[],
 @args=[],
 @behavior=:invoke,
 @destination_stack=["/Volumes/Work/dev/ewok"],
 @in_group=nil,
 @options={},
 @shell=#, @mute=false, @padding=0>>
 pry(main)> g.send(:class_collisions, 'ActiveRecord')
Rails::Generators::Error: The name 'ActiveRecord' is either already used in your application or reserved by Ruby on Rails. Please choose an alternative and run this generator again.
pry(main)> g.send(:class_collisions, 'type')
=> ["type"]
pry(main)> g.send(:class_collisions, 'ActiveRecord', 'ActiveJob')
Rails::Generators::Error: The name 'ActiveRecord' is either already used in your application or reserved by Ruby on Rails. Please choose an alternative and run this generator again.