配置session_store.rb来处理登台和生产?

sno*_*gel 11 cookies session ruby-on-rails ruby-on-rails-3.1

我在我的rails 3.1rc6应用程序上有一个使用子域的登台和生产环境.我为这些环境购买并配置了不同的域名,因为默认的something-something.herokuapp.com不能很好地与子域名一起使用.

当我为一个环境设置session_store.rb时,一切正常:

AppName::Application.config.session_store :cookie_store, :key => '_sample_app_session' , :domain => '.mystagingdomain.co.uk' 
Run Code Online (Sandbox Code Playgroud)

但我似乎无法在条件中添加允许特定于环境的域名.

我试过了

AppName::Application.config.session_store :cookie_store, :key => '_sample_app_session' , :domain => '.mystagingdomain.co.uk' if Rails.env.staging?
AppName::Application.config.session_store :cookie_store, :key => '_sample_app_session' , :domain => '.myproductiondomain.com' if Rails.env.production?
Run Code Online (Sandbox Code Playgroud)

这不起作用.

Aru*_*nan 17

以下设置对我来说很好:

配置/环境/ staging.rb

AppName::Application.config.session_store :cookie_store, :key => '_sample_app_session' , :domain => '.mystagingdomain.co.uk'
Run Code Online (Sandbox Code Playgroud)

配置/环境/ production.rb

AppName::Application.config.session_store :cookie_store, :key => '_sample_app_session' , :domain => '.myproductiondomain.com'
Run Code Online (Sandbox Code Playgroud)


Sim*_*tti 6

您可以使用该:domain => :all选项.:tld_length如果不同于1,您还可以提供.

AppName::Application.config.session_store :cookie_store, :key => '_sample_app_session' , :domain => :all
Run Code Online (Sandbox Code Playgroud)

这是相关的Rails代码

def handle_options(options) #:nodoc:
  options[:path] ||= "/"

  if options[:domain] == :all
    # if there is a provided tld length then we use it otherwise default domain regexp
    domain_regexp = options[:tld_length] ? /([^.]+\.?){#{options[:tld_length]}}$/ : DOMAIN_REGEXP

    # if host is not ip and matches domain regexp
    # (ip confirms to domain regexp so we explicitly check for ip)
    options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ domain_regexp)
      ".#{$&}"
    end
  elsif options[:domain].is_a? Array
    # if host matches one of the supplied domains without a dot in front of it
    options[:domain] = options[:domain].find {|domain| @host.include? domain[/^\.?(.*)$/, 1] }
  end
end
Run Code Online (Sandbox Code Playgroud)

否则,您还应该能够config/environments/ENVIRONMENT.rb基于每个环境覆盖文件中的设置.

  • 我想在这里添加这个答案对我有所帮助.如果您正在使用辅助域lvh.me为您的子域开发,它将通过DOMAIN_REGEXP解释为TLD,因此不会模仿example.com,它的行为类似于example.com.au所以您需要通过tld_length为1 [Github source](https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/middleware/cookies.rb#L103) (2认同)