How to run JavaScript function in before_save filter to replace some value before saving into database?
-
12-12-2019 - |
Question
I have categoried, which user choose. If user choose 'Auto' I need to replace it with result, what gives me my JavaScript function - setting default browser language.
Here is JavaScript example, of JS function - http://fiddle.jshell.net/xCgsb/
And here is my before_save filter in Website model:
before_save :auto_language
def create
website = current_user.websites.new params[:website]
if @website.language == "Auto"
@website.language = request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
end
...
#error
undefined local variable or method `request' for #<Website:0x244e1b0>
Can someone help me with this trouble ? Any help appreciated.
Solution
You should not be using Javascript to set up your default locale.
Take a look at this:
http://guides.rubyonrails.org/i18n.html#setting-the-locale-from-the-client-supplied-information
They use Ruby to detect the locale
def set_locale
logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}"
I18n.locale = extract_locale_from_accept_language_header
logger.debug "* Locale set to '#{I18n.locale}'"
end
private
def extract_locale_from_accept_language_header
request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
end
If you want to get the full language, you can use a switch case:
def full_language_name(lang)
case lang
when 'ru'
return 'Russian'
when 'en'
return 'English'
when 'fr'
return 'French'
else
return 'English'
end
The 'else' case is the default behavior if none of these conditions has been verified. The keyword 'return' is optional.
Hope this helps!