Skip to content

Commit

Permalink
Add URI.from_json_object_key? and URI#to_json_object_key (#14834)
Browse files Browse the repository at this point in the history
  • Loading branch information
nobodywasishere committed Aug 20, 2024
1 parent ee894e0 commit 41f75ca
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
14 changes: 14 additions & 0 deletions spec/std/uri/json_spec.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
require "spec"
require "uri/json"

describe "URI" do
describe "serializes" do
it "#to_json" do
URI.parse("https://example.com").to_json.should eq %q("https://example.com")
end

it "from_json_object_key?" do
URI.from_json_object_key?("https://example.com").should eq(URI.parse("https://example.com"))
end
end
end
14 changes: 14 additions & 0 deletions src/uri/json.cr
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,18 @@ class URI
def to_json(builder : JSON::Builder)
builder.string self
end

# Deserializes the given JSON *key* into a `URI`
#
# NOTE: `require "uri/json"` is required to opt-in to this feature.
def self.from_json_object_key?(key : String) : URI?
parse key
rescue URI::Error
nil
end

# :nodoc:
def to_json_object_key : String
to_s
end
end

0 comments on commit 41f75ca

Please sign in to comment.