How do I access the name of the Rails 3 application object?

Solution 1:

Rails <= 6.0

Rails.application.class.parent_name

Rails 6.1 and higher

Rails.application.class.module_parent_name

Solution 2:

The original poster asked for the name of the rails app, not for the class name. Those are two different things. e.g. the spelling of the rails app can be different from what Rails expects, e.g. 'test-app' instead of 'test_app'.

It is difficult to get to the name of the Rails App spelled the way as it was checked-in, because that name is not preserved. Only the options for the session_store seem to contain the original string slightly modified.

The best way to get to the name of the Rails application is:

This will work even if your app directory was renamed, or sym-linked!

Rails.application.config.session_options[:key].sub(/^_/,'').sub(/_session/,'')
=> "test-app"

Why? Because the author of the app could have spelled it's name differently than Rails expects... e.g. with '-' characters instead of '_'; e.g. "test-app". From the class name you can't guarantee to get to the correct spelling.

Using this info, you could do this:

class << Rails.application
  def name
    Rails.application.config.session_options[:key].sub(/^_/,'').sub(/_session/,'')
  end
end

Rails.application.name
=> 'test-app'

or just add this to your ./config/environment.rb:

APP_VERSION = '1.0.0'
APP_NAME = Rails.application.config.session_options[:key].sub(/^_/,'').sub(/_session/,'')

that makes these constants available on the top-level of the app.


Close, but no cigar:

This is almost correct, but it will still fail if the application directory gets renamed (e.g. during deployment to '"20121001_110512" or "latest"... then the following would break:

File.basename(Rails.root.to_s)
=> "test-app"

with the following two approaches you can't get to the correct spelling.. you could only guess a name:

This is sub-optimal, and can give incorrectly spelled results:

You can get to a derivative of the application name like this:

Rails.application.engine_name.gsub(/_application/,'')
=> "test_app"

But please note that this is not fool-proof, because somebody could have named the app "test-app" and you will see the result above, not the correct name with '-'.

Same thing is true if you derive it like this:

Rails.application.class.parent_name
=> "TestApp"

this is the class name, but you can't be sure how to get to the name the way the author spelled it.