🙆

Rails の String#underscore に :: が含まれているときの挙動

に公開

Rails の ActiveSupport の String#underscore は以下のように snake_case ライクに _ をつけた文字列に変換します。

require "active_support/core_ext/string"

pp "MasterUserAddress".underscore
# => "master_user_address"

:: が含まれている場合にどうなる?

対象の文字列が Master::User::Address のように :: がついている場合は / として変換がされます。

require "active_support/core_ext/string"

pp "Master::User::Address".underscore
# => "master/user/address"

また String#camelize/:: に変換します。

require "active_support/core_ext/string"

pp "master/user/address".camelize
# => "Master::User::Address"

知らなかった。
autoload とか考えると / のほうが都合がいいんですかねー。

GitHubで編集を提案

Discussion