Skip to content

Commit

Permalink
Optimize ConfigurationFile when ERB is not used
Browse files Browse the repository at this point in the history
`YAML.load` is much slower than `YAML.load_file` when Bootsnap
is enabled.

As such for big file that don't use ERB, it's preferable to use
`load_file`.

This is mostly useful for fixtures (which use `ConfigurationFile`
under the hood)
  • Loading branch information
byroot committed Aug 21, 2024
1 parent 888d284 commit b8924f6
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
14 changes: 11 additions & 3 deletions activesupport/lib/active_support/configuration_file.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,18 @@ def self.parse(content_path, **options)

def parse(context: nil, **options)
source = render(context)
if YAML.respond_to?(:unsafe_load)
YAML.unsafe_load(source, **options) || {}
if source == @content
if YAML.respond_to?(:unsafe_load)
YAML.unsafe_load_file(@content_path, **options) || {}
else
YAML.load_file(@content_path, **options) || {}
end
else
YAML.load(source, **options) || {}
if YAML.respond_to?(:unsafe_load)
YAML.unsafe_load(source, **options) || {}
else
YAML.load(source, **options) || {}
end
end
rescue Psych::SyntaxError => error
raise "YAML syntax error occurred while parsing #{@content_path}. " \
Expand Down
14 changes: 12 additions & 2 deletions activesupport/test/configuration_file_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ class ConfigurationFileTest < ActiveSupport::TestCase
test "backtrace contains YAML path" do
Tempfile.create do |file|
file.write("wrong: <%= foo %>")
file.rewind
file.flush

error = assert_raises do
ActiveSupport::ConfigurationFile.parse(file.path)
Expand All @@ -19,7 +19,7 @@ class ConfigurationFileTest < ActiveSupport::TestCase
test "backtrace contains YAML path (when Pathname given)" do
Tempfile.create do |file|
file.write("wrong: <%= foo %>")
file.rewind
file.flush

error = assert_raises do
ActiveSupport::ConfigurationFile.parse(Pathname(file.path))
Expand All @@ -28,4 +28,14 @@ class ConfigurationFileTest < ActiveSupport::TestCase
assert_match file.path, error.backtrace.first
end
end

test "load raw YAML" do
Tempfile.create do |file|
file.write("ok: 42")
file.flush

data = ActiveSupport::ConfigurationFile.parse(Pathname(file.path))
assert_equal({ "ok" => 42 }, data)
end
end
end

0 comments on commit b8924f6

Please sign in to comment.