【问题标题】:Creating a rails route to an external URL in Rails 4在 Rails 4 中创建到外部 URL 的 rails 路由
【发布时间】:2015-10-12 13:37:35
【问题描述】:

我有一堆路由(~50)需要映射到外部 URL。我绝对可以按照here 中的建议进行操作,但这会使我的 routes.rb 文件变得混乱。有什么办法可以将它们放在配置文件中并从我的 routes.rb 文件中引用它?

另外,当映射到外部 URL 时,如果是非生产环境,则需要映射到“http:example-test.com/..”,生产模式需要映射到“http:example.com”。 com/...”。我知道我可以在 config 中有一个 yml 文件来处理不同的环境。但是如何在我的 routes.rb 文件中访问它?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    首先让我们为外部主机创建一个自定义配置变量:

    # config/application.rb
    module MyApp
      class Application < Rails::Application
        config.external_host = ENV["EXTERNAL_HOST"]
      end
    end
    

    然后让我们根据环境进行设置:

    # config/environments/development.rb
    Rails.application.configure do
      # ...
      config.external_host ||= 'dev.example.com'
    end
    
    # config/environments/test.rb
    Rails.application.configure do
      # ...
      config.external_host ||= 'test.example.com'
    end
    
    # config/environments/production.rb
    Rails.application.configure do
      # ...
      config.external_host ||= 'example.com'
    end
    

    然后我们设置路线:

    Rails.application.routes.draw do
      # External urls
      scope host: Rails.configuration.external_host do
        get 'thing' => 'dev#null', as: :thing
      end
    end
    

    让我们试试吧:

    $ rake routes
    Prefix Verb URI Pattern      Controller#Action
     thing GET  /thing(.:format) dev#null {:host=>"dev.example.com"}
    $ rake routes RAILS_ENV=test
    Prefix Verb URI Pattern      Controller#Action
     thing GET  /thing(.:format) dev#null {:host=>"test.example.com"}
    $ rake routes RAILS_ENV=production
    Prefix Verb URI Pattern      Controller#Action
     thing GET  /thing(.:format) dev#null {:host=>"example.com"}
    $ rake routes EXTERNAL_HOST=foobar
    Prefix Verb URI Pattern      Controller#Action
     thing GET  /thing(.:format) dev#null {:host=>"foobar"}
    

    【讨论】:

      【解决方案2】:

      试试这个。希望这对你有用..

      MyApp::Application.routes.draw do
        # External urls
        scope host: 'www.example.com' do
          get 'thing' => 'dev#null', as: :thing
        end
      end
      
      # Use thing_url in your veiws (thing_path would not include the host)
      # thing_url => "http://www.example.com/thing"
      

      【讨论】:

      • 您可以通过输入像scope host: (Rails.env.production? ? 'www.example.com' : 'example-test.com') do这样的第三级语句来处理此处的生产/非生产要求
      • 好主意@MaxWilliams,但我会使用配置变量:scope host: Rails.configuration.external_host。然后您可以在/config/development.rb、/config/production.rb 中设置不同的值...
      • 这将是一个自定义配置参数。看我的回答。
      • 谢谢@max。我刚刚看到那个弹出并删除了我的评论。这完美地回答了我的问题。
      • 是的,这比内联第三级语句更简洁。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多