LoginSignup
4
0

More than 5 years have passed since last update.

Yesodの設定ファイルconfig/settings.ymlに設定を追加する

Last updated at Posted at 2016-12-19

stackのテンプレートから生成したYesodアプリは、設定ファイル群が config ディレクトリに格納されています。

その中に settings.yml というファイルがあり、これは環境変数から値を取ったり、直接値を書いたりできる設定ファイルです。

今回はこのファイルに設定を追加する方法を紹介します。

config/settings.ymlの内容

デフォルトではsettings.ymlの内容は次のようになっています(DBにSqliteを使う場合。コメントは省いてあります)。

static-dir:     "_env:STATIC_DIR:static"
host:           "_env:HOST:*4" # any IPv4 host
port:           "_env:PORT:3000" # NB: The port `yesod devel` uses is distinct from this value. Set the `yesod devel` port from the command line.
ip-from-header: "_env:IP_FROM_HEADER:false"

#approot:        "_env:APPROOT:http://localhost:3000"

database:
  database: "_env:SQLITE_DATABASE:model-example.sqlite3"
  poolsize: "_env:SQLITE_POOLSIZE:10"

copyright: Insert copyright statement here
#analytics: UA-YOURCODE

値の書き方に注目すると

"_env:SQLITE_POOLSIZE:10"

という書き方は、「まず環境変数 SQLITE_POOLSIZE から値を取得し、失敗した場合は 10 を採用」という意味です。

AppSettings型で設定内容を受ける

settings.ymlの内容は、Settings.hsの中で定義されているAppSettings型で受け取ることができます。デフォルトでは次のような定義になっています(DBにSqliteを使う場合。コメントと空白行は省いてあります)。

data AppSettings = AppSettings
    { appStaticDir              :: String
    , appDatabaseConf           :: SqliteConf
    , appRoot                   :: Maybe Text
    , appHost                   :: HostPreference
    , appPort                   :: Int
    , appIpFromHeader           :: Bool
    , appDetailedRequestLogging :: Bool
    , appShouldLogAll           :: Bool
    , appReloadTemplates        :: Bool
    , appMutableStatic          :: Bool
    , appSkipCombining          :: Bool
    , appCopyright              :: Text
    , appAnalytics              :: Maybe Text
    , appAuthDummyLogin         :: Bool
    }

settings.ymlと同じ内容になっていることが分かると思います。
また、settigs.ymlに無いかもしれない設定は、型がMaybeになっています(appAnalytics が該当)。
また、入れ子になった設定も可能です(appDatabaseConf が該当)。

設定を追加する

設定を追加するには、ここまでで紹介した2つのファイルに追記すればOKです。
ここでは apiKey という設定を追加してみます。

settings.ymlに追記

apiKey: "_env:API_KEY:xxx-xxx-xxx-xxx"

Setting.hsのAppSettings型に追記

    , appApiKey                 :: String

AppSettingsを使う

AppSettingsは、Handler関数の中で簡単に使えます。

apiKey <- getYesod >>= return . appStaticDir . appApiKey
4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0