Setting Rails time zone in an initializer does not work? - ruby-on-rails

Since Rails 5 the application.rb tells me to place my app's configuration in initializers. In order to follow this convention, I wanted to set my timezone in an initializer.
config/initializers/time_zone.rb
Rails.application.config.time_zone = "Paris"
Rails seems to ignore this setting and keeps its default time zone. Using the same code inside of my application.rb works. Why is the initializer being ignored?

Per Rails5 guide it should be configured in config/application.rb file.
#application.rb
class Application < Rails::Application
config.time_zone = 'Paris'
end

Related

How to define application configurations in Rails 5?

I've normally put settings like the below in config/application.rb
config.generators.stylesheets = false
config.time_zone = 'Berlin'
But in Rails 5 the message below is found in config/application.rb
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
What does this mean? Am I supposed to add an initializer-file for every config setting? And in that case, what should such a file contain?
You should still be able to put the configuration in your config/application.rb, however the message is informing you that your environment specific configurations take precedence over those specified there, so if you have another configuration overriding any of such values in your config/environments those in the environment specific would be used.
If you're using the initializers approach, in your config/initializers/stylesheet_generator.rb, you'd have:
Rails.application.config.generators.stylesheets = false
and in your config/initializers/time_zone.rb, you'd have:
Rails.application.config.time_zone = 'Berlin'

How to reload Application Class in Ruby on Rails

I noticed that my configuration which was parsed from a yml file is not being reloaded when I start up a console. Here is my application.rb file:
module MyApp
def self.config
Rails.application.config.yml_data['common']
end
class Application < Rails::Application
config.yml_data = YAML.load(ERB.new(File.read(Rails.root.join('config', 'platform', 'config.yml'))).result)
config.autoload_paths += Dir["#{config.root}/lib/**/"]
end
end
I have config.cache_classes set to false. Is there a way to reload MyApp ??? The config never gets updated.
If you change things while the rails console is opened it will not automatically reload them. You have to use the command reload!
If it wasn’t what you are trying to do, please explain it with more detail.
Try adding your config file path to config.autoload_paths like its said on documentation

Rails: Have initializer load before application.rb

I have an initializer named _settings.rb that looks like this
class Settings < Settingslogic
source "#{Rails.root}/config/application.yml"
namespace Rails.env
end
My application.yml defines a value for a custom setting I call environhost.
I call it using:
Settings.environhost
This works fine, EXCEPT for when I try to call the value in my /app/config/application.rb
config.action_controller.asset_host = Settings.environhost
For this, I get an uninitialized constant.
Is there anyway I can put a pointer in my application.rb to load _settings.rb before
config.action_controller.asset_host = Settings.environhost
is loaded? What's the best way to do this?
http://guides.rubyonrails.org/initialization.html
Rails own configuration will be always loaded before any custom things, that's for sure. Otherwise can you imagine what a mess :)
The solution is not to try to load before Rails configuration. Instead, hook into initializer to add your own logic to override Rails default.
Railtie is the place you can do that without sweat. Here you can access config method shared in all initializers including Rails.
module MySettings
def self.environhost
"foobar"
end
class MySettingsRailtie < Rails::Railtie
config.action_controller.asset_host = MySettings.environhost
end
end
Side note: In most cases you should be fine to set assets host as mu_is_too_short commented. If you need anything other than that, you can use custom intializer by Railtie.

Rails: How to set default timezone to a specific one for the whole application?

How do I set default timezone for Rails and ActiveRecord? I have a lot of places where time is diplayed(for example creation of some instance in the database, etc.). The time is displayed in my current timezone. Should i somehow configure Rails/ActiveRecord or *nix distributive that i am using on hosting platform?
I've tryied to add that to application.rb file without any result:
config.time_zone = 'Moscow'
config.active_record.default_timezone = :local
I've also tried to use
config.time_zone = 'Moscow'
config.active_record.default_timezone = "Moscow"
But in that case i get a warning
warning: :database_timezone option must be :utc or :local - defaulting to :local
Is there a solution that will prevent me from changing all those places where time is rendered?
Just try using the below given one only in application.rb,
config.active_record.default_timezone = :local
discard,
config.time_zone
May that help you.
First off: I'm always for not messing with the way AR stores time stamps, because Rails already does all the magic about time conversion for you.
I assume you want to display the times in your app in the time zone the current user has selected (or that you have determined per-user in some other way). In that case what you configured in config.time_zone is of no consequence, because you obviously want to overwrite it. Rails has a neat mechanism for this called Time.use_zone.
I used that in an around_filter before, like this:
around_filter :set_time_zone
def set_time_zone
Time.use_zone(current_user.try(:time_zone) || Time.zone) do
yield
end
end
This sets the time zone for the current request to the current_user's time_zone if that user is present. Falls back to the time zone configured in application.rb otherwise.
Inside the Time.use_zone block, all times are displayed and saved as in that zone.
What's very handy about this approach is that after each request the time zone is reset to what is configured. If you'd just change Time.zone and wouldn't bother resetting it, it can potentially leak to other users.
I suggest you try this and see if it does what you want before trying to wrap your head around what all this means, because that can make your head spin. I'm happy to explain more about the how and why, if you're interested, though.

How to change default timezone for Active Record in Rails?

In my application.rb I came across the following comment
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = 'Eastern Time (US & Canada)'
As you see from above, I've made config.time_zone to EST time. However, still when records are created in the DB, it looks like datetime is being stored in UTC format.
In the above comment, they say
...and make Active Record auto-convert to this zone...
How can I do that, and where?
Also, I'll be deploying this on heroku as well and i'd like the setting to carry over
I have decided to compile this answer because all others seem to be incomplete.
config.active_record.default_timezone determines whether to use Time.local (if set to :local) or Time.utc (if set to :utc) when pulling dates and times from the database. The default is :utc.
http://guides.rubyonrails.org/configuring.html
If you want to change Rails timezone, but continue to have Active Record save in the database in UTC, use
# application.rb
config.time_zone = 'Eastern Time (US & Canada)'
If you want to change Rails timezone AND have Active Record store times in this timezone, use
# application.rb
config.time_zone = 'Eastern Time (US & Canada)'
config.active_record.default_timezone = :local
Warning: you really should think twice, even thrice, before saving times in the database in a non-UTC format.
Note
Do not forget to restart your Rails server after modifying application.rb.
Remember that config.active_record.default_timezone can take only two values
:local (converts to the timezone defined in config.time_zone)
:utc (converts to UTC)
Here's how you can find all available timezones
rake time:zones:all
adding following to application.rb works
config.time_zone = 'Eastern Time (US & Canada)'
config.active_record.default_timezone = :local # Or :utc
I came to the same conclusion as Dean Perry after much anguish. config.time_zone = 'Adelaide' and config.active_record.default_timezone = :local was the winning combination. Here's what I found during the process.
In my case (Rails 5), I ended up adding these 2 lines in my app/config/environments/development.rb
config.time_zone = "Melbourne"
config.active_record.default_timezone = :local
That's it! And to make sure that Melbourne was read correctly, I ran the command in my terminal:
bundle exec rake time:zones:all
and Melbourne was listing in the timezone I'm in!
If you want to set the timezone to UTC globally, you can do the following in Rails 4:
# Inside config/application.rb
config.time_zone = "UTC"
config.active_record.default_timezone = :utc
Be sure to restart your application or you won't see the changes.
I had to add this block to my environment.rb file and all was well :)
Rails.application.configure do
config.time_zone = "Pacific Time (US & Canada)"
config.active_record.default_timezone = :local
end
I added it before the line Rails.application.initialize!
In Ruby on Rails 6.0.1 go to config > locales > application.rb and add the following:
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module CrudRubyOnRails6
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0
config.active_record.default_timezone = :local
config.time_zone = 'Lima'
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
end
end
You can see that I am configuring the time zone with 2 lines:
config.active_record.default_timezone =: local
config.time_zone = 'Lima'
I hope it helps those who are working with Ruby on Rails 6.0.1
On rails 4.2.2, go to application.rb and use config.time_zone='city' (e.g.:'London' or 'Bucharest' or 'Amsterdam' and so on).
It should work just fine. It worked for me.
for Chinese user, just add two lines below to you config/application.rb :
config.active_record.default_timezone = :local
config.time_zone = 'Beijing'
If you want local time to set, add the following text in application.rb
config.time_zone = 'Chennai'
# WARNING: This changes the way times are stored in the database (not recommended)
config.active_record.default_timezone = :local
Then restart your server

Resources