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

后端 未结 8 930
礼貌的吻别
礼貌的吻别 2020-12-23 13:28

I need to know the name of a programmers application from within a Rails 3 engine.

8条回答
  •  既然无缘
    2020-12-23 13:49

    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.

提交回复
热议问题