Набор констант в environment.rb исчезает в режиме разработки

Вы правы в том, что это неправильно!

Это даст вам правильный результат, но давайте посмотрим, что на самом деле происходит.

  if guess == item:
    return mid
  if guess > item:
    high = mid - 1
  else:
    low = mid + 1

На первой итерации, guess == list[mid] == list[high] == 9. 3 меньше 9, так что высокий будет уменьшаться.

В следующей итерации, снова mid == high, но высокий на 1 меньше.

высокий будет продолжать уменьшаться до guess == list[mid] == list[high] == list[1] == 3

5
задан joshuaxls 14 April 2009 в 05:57
поделиться

2 ответа

It only works on the first request in development mode because the classes are reloaded on each request. So on the first request the constant is set in the initializer, and all is good. Then on the next request, it reloads the class WITHOUT rerunning the bit from your initializer, so the constant isn't set from there on out.

It works in production mode because the classes aren't reloaded for each request, so you don't lose that bit of class state each time.

So you might want to set the constant either in the model, or in a config.to_prepare instead config.after_initialize. to_prepare is called before each request.

In the model:

class SomeClass < ActiveRecord::Base
  MY_CONST = "whatever"

  # You can access MY_CONST directly, but I tend to wrap them in a class 
  # method because literal constants often get refactored into the database.
  def self.my_const
    MY_CONST 
  end
end

In the config:

# This will run before every single request. You probably only want this in
# the development config.
config.to_prepare do
  SomeClass.const_set 'SOME_CONST', 'SOME_VAL'
end
9
ответ дан 13 December 2019 в 22:16
поделиться

В производственном режиме предварительно загружаются все классы, тогда как в режиме разработки классы загружаются по мере необходимости, после считываются файлы конфигурации. Требование их вручную в конфигах заставляет читать классы до / во время стадии конфигурирования.

1
ответ дан 13 December 2019 в 22:16
поделиться
Другие вопросы по тегам:

Похожие вопросы: