Json: Add #parse_json method
This setup mimics the `#parse_xml` method that was implemented in the `Xml` strategy. Isolating the parsing code means that other strategies can take only what they need from `Json` (i.e., it's not required for them to use `Json#find_versions`).
This commit is contained in:
parent
97fbd89a57
commit
cebb951baf
@ -46,6 +46,19 @@ module Homebrew
|
|||||||
URL_MATCH_REGEX.match?(url)
|
URL_MATCH_REGEX.match?(url)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# Parses JSON text and returns the parsed data.
|
||||||
|
# @param content [String] the JSON text to parse
|
||||||
|
sig { params(content: String).returns(T.untyped) }
|
||||||
|
def self.parse_json(content)
|
||||||
|
require "json"
|
||||||
|
|
||||||
|
begin
|
||||||
|
JSON.parse(content)
|
||||||
|
rescue JSON::ParserError
|
||||||
|
raise "Content could not be parsed as JSON."
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
# Parses JSON text and identifies versions using a `strategy` block.
|
# Parses JSON text and identifies versions using a `strategy` block.
|
||||||
# If a regex is provided, it will be passed as the second argument to
|
# If a regex is provided, it will be passed as the second argument to
|
||||||
# the `strategy` block (after the parsed JSON data).
|
# the `strategy` block (after the parsed JSON data).
|
||||||
@ -63,12 +76,8 @@ module Homebrew
|
|||||||
def self.versions_from_content(content, regex = nil, &block)
|
def self.versions_from_content(content, regex = nil, &block)
|
||||||
return [] if content.blank? || block.blank?
|
return [] if content.blank? || block.blank?
|
||||||
|
|
||||||
require "json"
|
json = parse_json(content)
|
||||||
json = begin
|
return [] if json.blank?
|
||||||
JSON.parse(content)
|
|
||||||
rescue JSON::ParserError
|
|
||||||
raise "Content could not be parsed as JSON."
|
|
||||||
end
|
|
||||||
|
|
||||||
block_return_value = if regex.present?
|
block_return_value = if regex.present?
|
||||||
yield(json, regex)
|
yield(json, regex)
|
||||||
|
@ -74,6 +74,12 @@ describe Homebrew::Livecheck::Strategy::Json do
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
describe "::parse_json" do
|
||||||
|
it "returns an object when given valid content" do
|
||||||
|
expect(json.parse_json(content_simple)).to be_an_instance_of(Hash)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
describe "::versions_from_content" do
|
describe "::versions_from_content" do
|
||||||
it "returns an empty array when given a block but content is blank" do
|
it "returns an empty array when given a block but content is blank" do
|
||||||
expect(json.versions_from_content("", regex) { "1.2.3" }).to eq([])
|
expect(json.versions_from_content("", regex) { "1.2.3" }).to eq([])
|
||||||
|
Loading…
x
Reference in New Issue
Block a user