iT邦幫忙

2022 iThome 鐵人賽

DAY 24
0
Modern Web

Rails,我要進來囉系列 第 24

第二十四天:Rails 的各種神奇設定 - Rails Configuration

  • 分享至 

  • xImage
  •  

開場白

鼬~~哩賀,我是寫程式的山姆老弟,昨天跟大家一起看了 Rails 的 Command Line 有哪些特殊指令,今天來看看 Rails 的各種設定,像是你們在 config/application.rb 或是 config/environments/development.rb 之中會看到的各種 config.xxxx = true 一樣,夠夠~

https://raw.githubusercontent.com/shrimp509/my-img-host/master/relacs-studio/Rails%E6%88%91%E8%A6%81%E9%80%B2%E4%BE%86%E5%9B%89/day24-1.png

ps. 這一篇超級無敵長,我就挑我自己覺得有用的、很驚艷的來介紹XD

ps. 本篇使用的「設定檔」字眼,將會等於

  • config/application.rb
  • config/environments/development.rb
  • config/environments/test.rb
  • config/environments/production.rb
  • 其他環境設定檔(config/environments/*.rb)

ps. 以下設定後面接的括號,將會是這個設定所需要輸入的格式,例如 config.beginning_of_week (Symbol),這個設定的使用方式就是 config.beginning_of_week = :sunday

General (就是我不知道怎麼分類的都會在這裡 XD)

  • config.beginning_of_week (Symbol), default: :monday
  • config.after_initialize (Block), default: nil
  • config.console (Class), default: nil
  • config.disable_sandbox (Boolean), default: false
  • config.encoding (String), default: UTF-8
  • config.force_ssl (Boolean), default: false
  • config.middleware (Instance), default: ActionDispatch::MiddlewareStack
  • config.credentials.content_path (Instance), default: Pathname('config/credentials.yml.enc')
  • config.credentials.key_path (Instance), default: Pathname('config/master.key')
  • config.secret_key_base (?), default: nil
  • config.require_master_key (Boolean), default: false
  • config.ssl_options (Hash), default: {:hsts=>{:subdomains=>true}} (從 Rails 5.0 以後都是這個預設值)
  • config.time_zone (String), default: 'UTC'

Assets

  • config.asset_host (String), default: nil
  • config.javascript_path (String), default: 'javascript'
  • config.public_file_server.enabled (Boolean), default: true in development,false in production
  • config.assets.css_compressor (Symbol), default: sass-rails
  • config.assets.js_compressor (Symbol), default: ?
  • config.assets.gzip (Boolean), default: true
  • config.assets.paths (Array), default: [.../javascript, .../images, .../stylesheets]
  • config.assets.precompile (Array), default: ["manifest.js", "turbo.js", "turbo.min.js", "turbo.min.js.map", "actiontext.js", "trix.js", "trix.css", "es-module-shims.js", "es-module-shims.min.js", "es-module-shims.js.map", "stimulus.js", "stimulus.min.js", "stimulus.min.js.map", "activestorage", "activestorage.esm", "actioncable.js", "actioncable.esm.js"]
  • config.assets.unknown_asset_fallback (Boolean), default: false (從 Rails 5.1 以後都是這個預設值)
  • config.assets.prefix (String), default: '/assets'
  • config.assets.manifest (String), default: ?
  • config.assets.digest (Boolean), default: true
  • config.assets.debug (Boolean), default: true in development, false in production
  • config.assets.version (String), default: 1.0
  • config.assets.compile (Boolean), default: true in development, false in production
  • config.assets.logger (Class/Boolean), default: Logger
  • config.assets.quiet (Boolean), default: true in development, false in production

Loading

  • config.autoload_once_paths (Array), default: []
  • config.autoload_paths (Array), default: []
  • config.add_autoload_paths_to_load_path(Boolean), default: true
  • config.eager_load (Boolean), default: false in development, true in production
  • config.eager_load_namespaces (Array), default: [I18n, ActiveSupport, ActionDispatch, ActiveModel, ActionView::Railtie, ActionView, ActionController, ActiveRecord, GlobalID, ActiveStorage::Engine, ActiveStorage, ActionMailer, ActionCable::Engine, ActionCable, ActionMailbox::Engine, ActionMailbox, ActionText::Engine, ActionText, Importmap::Engine, Turbo::Engine, Turbo, Stimulus::Engine, Rails7Minitest::Application]
  • config.eager_load_paths (Array), default: ["app/channels", "app/controllers", "app/controllers/concerns", "app/helpers", "app/jobs", "app/mailers", "app/models", "app/models/concerns]
  • config.enable_dependency_loading (Boolean), default: false
  • config.rake_eager_load (Boolean), default: false
  • config.reload_classes_only_on_change (Boolean), default: true

Caching

  • config.cache_store (Symbol), default: :file_store
  • config.cache_classes (Array), default: false in development, true in production
  • config.session_store (Symbol), default: :cookie_store,還有 :mem_cache_store, :your_custom_store, :disabled 可以選填

Debugging

  • config.consider_all_requests_local (Boolean), default: true in development, false in production

  • config.colorize_logging (Boolean), default: true

  • config.exceptions_app (Class), default: nil

  • config.debug_exception_response_format (Symbol), default: :default,:api for API only apps

  • config.file_watcher (Class), default: ActiveSupport::FileUpdateChecker

  • config.filter_parameters (Array), default: [],但 Rails 預設會建立 config/initializers/filter_parameter_logging.rb

    # config/initializers/filter_parameter_logging.rb
    Rails.application.config.filter_parameters += [
      :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn
    ]
    
  • config.log_formatter (Instance), default: ActiveSupport::Logger::SimpleFormatter

  • config.log_level (Symbol), default: :debug in development & test, :info in production,可帶入的有 :debug, :info, :warn, :error, :fatal, :unknown

  • config.log_tags (Array), default: []

  • config.logger (Instance), default: ActiveSupport::TaggedLogging

值得注意的點

  • 可以在設定檔使用 console block,這個 block 只有在 $ rails console 才會執行

    # config/application.rb
    module YourApplicationName
      class Application < Rails::Application
    		console do
    			puts("Only called when using '$ rails console'. This is cool!")
    		end
      end
    end
    
  • 在設定檔中可以使用的 initialization event,不只有 after_initialize block,還有 before_configuration, before_initialize, to_prepare, before_eager_load

  • 可以透過 config.x(這邊一定要用 x),把自己的設定放在 Rails 的設定中

    # config/application.rb
    module MyApp
      class Application < Rails::Application
    		...
        config.x.payment = { 
          environment: 'sandbox',
          merchant_id: 'development_merchant_id',
          public_key:  'development_public_key',
          private_key: 'development_private_key'
        }
      end
    end
    
    # $ rails console
    # [1] pry(main)> Rails.configuration.x.payment[:environment] # sandbox
    

總結

Rails 提供的細節設定有 超級無敵多,強烈推薦大家去「逛逛」 ,我這篇文章裡面寫的,大概只佔 RailsGuide 的 1/20 而已吧,其他還有關於 middleware, i18n, active_record, action_controller, action_dispatch, action_view, action_mailbox, action_mailer, active_support, active_job, action_cable, active_storage, action_text, database 各種的設定,去看看 Rails 還有哪些奇葩的設定,是一種劉姥姥進大觀園的概念XD,不需要把這些設定記下來、也不需要全部的設定都去理解,大部分的開發者沒事不會需要調這些設定,但當有需求的時候,就會用到這些設定,所以在有需求之前,還是先去了解有哪些設定可以調整,等到了有需求的時候,就知道可以怎麼調、去哪裡找文件來調整

這一篇 RailsGuide 還有另一種用途,就是當作工具書來使用,當有需求要做一些客製化的設定,就來這篇搜尋關鍵字,看有沒有現成的設定可以直接調,不過比較麻煩的是各個設定之間,可能會打架,所以調整設定之前,要仔細看一下說明

那今天就先這樣囉,我們明天見~


上一篇
第二十三天:Rails 的 Command Line 工具,發現好多酷東東
下一篇
第二十五天:Rack 到底是什麼?跟 Rails 有什麼關係?那 Rake 又是什麼?
系列文
Rails,我要進來囉30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言