Setting default_url_options for mounted Rails engine
Asked Answered
B

2

5

Using rails 3.2.13 and spree 2.0.2
I've encountered the similar problem as in Rails mountable engine under a dynamic scope

My routes:

scope ':locale', locale: /en|jp/ do
  mount Spree::Core::Engine, at: '/store'
  root to: 'home#index'
end

I want to output link to change locale:

<%= link_to 'JP', url_for(locale: :jp) %>

but this outputs:

<a href="/en/store/?locale=jp">JP</a>

instead of expected:

<a href="/jp/store">JP</a>

-- Edit --

When I put to ApplicationController:

def default_url_options(options={})
  { locale: I18n.locale }
end

it sets locale params in store twice instead of merging them:

http://localhost:3000/en/store/products/bag?locale=en
Bowse answered 20/6, 2013 at 6:56 Comment(4)
Do you had any luck to solve your problem? Cause I have the same problem as you at the moment. Thanks in advanceGlidebomb
No. Please upvote for visibility.Bowse
I hope it will help! ;-)Glidebomb
Solution here #18004126Stratagem
R
1

Faced exactly the same problem and I have found a solution for that...

Here is my application_controller-File (my engines inherit from this file (which is the Main Apps ApplicationController, so that I don't have code-duplication)

#!/bin/env ruby
# encoding: utf-8
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  before_filter :set_locale_from_params

  def url_options
    { locale: I18n.locale }
  end

  protected
    def set_locale_from_params
      if params[:locale]
        if I18n.available_locales.include?(params[:locale].to_sym)
          I18n.locale = params[:locale]
        else
          flash.now[:notice] = 'Translation not available'
          logger.error flash.now[:notice]
        end
      end
    end
end

Note, that the url_options-code is outside the protected part. It has to be public.

Found the tipps for the solution here: default_url_options and rails 3

Hope it helps

Regards

Philipp

Riendeau answered 18/8, 2013 at 14:12 Comment(1)
for some reason I was only experiencing this problem in my specs, and this helped, I just changed to before_filter :set_locale_from_params, if: Rails.env == "test"Hereinbefore
W
1

To set the default_url_options for an engine like Spree. You need to target the engine and set the parameter.

For example, to set the host.

    # config/environment/development.rb
 
    Spree::Core::Engine.routes.default_url_options[:host] = "localhost:3000"
Welsh answered 8/12, 2021 at 21:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.