Skip to content
This repository has been archived by the owner on Jul 27, 2024. It is now read-only.

Write JSON to file, not a Ruby Hash. #434

Merged
merged 1 commit into from
Sep 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/theme_check/corrector.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def create(theme, relative_path, content)

def create_default_locale_json(theme)
theme.default_locale_json = JsonFile.new("locales/#{theme.default_locale}.default.json", theme.storage)
theme.default_locale_json.update_contents('{}')
theme.default_locale_json.update_contents({})
end
end
end
13 changes: 9 additions & 4 deletions lib/theme_check/json_file.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,19 @@ def parse_error
@parser_error
end

def update_contents(new_content = '{}')
def update_contents(new_content = {})
raise ArgumentError if new_content.is_a?(String)
@content = new_content
end

def write
if source != @content
@storage.write(@relative_path, content)
@source = content
pretty = JSON.pretty_generate(@content)
if source.rstrip != pretty.rstrip
# Most editors add a trailing \n at the end of files. Here we
# try to maintain the convention.
eof = source.end_with?("\n") ? "\n" : ""
@storage.write(@relative_path, pretty + eof)
@source = pretty
end
end

Expand Down
9 changes: 9 additions & 0 deletions test/json_file_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,15 @@ def test_parse_error_with_error
assert_instance_of(JSON::ParserError, @json.parse_error)
end

def test_write
storage = make_storage("a.json" => '{ "hello": "world" }')
expected = { hello: "friend" }
@json = ThemeCheck::JsonFile.new("a.json", storage)
@json.update_contents(expected)
@json.write
assert_equal(JSON.pretty_generate(expected), storage.read("a.json"))
end

private

def make_json_file(name, content)
Expand Down