Complete implementation; add specs (#16081)

This commit is contained in:
Arit Amana 2022-01-12 15:45:59 -05:00 committed by GitHub
parent 2ca662cc5b
commit a4f12d39d9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 35 additions and 2 deletions

View file

@ -1,9 +1,14 @@
class CommentTag < LiquidTagBase
PARTIAL = "comments/liquid".freeze
REGISTRY_REGEXP = %r{#{URL.url}/\w+/comment/(?<comment_id>\w+)}
VALID_ID_REGEXP = /\A(?<comment_id>\w+)\Z/
REGEXP_OPTIONS = [REGISTRY_REGEXP, VALID_ID_REGEXP].freeze
def initialize(_tag_name, id_code, _parse_context)
super
@comment = find_comment(id_code.strip)
input = CGI.unescape_html(strip_tags(id_code))
@comment = find_comment(parse_id_code(input))
end
def render(_context)
@ -16,8 +21,19 @@ class CommentTag < LiquidTagBase
def find_comment(id_code)
Comment.find_by(id_code: id_code)
end
private
def parse_id_code(input)
match = pattern_match_for(input, REGEXP_OPTIONS)
raise StandardError, "Invalid Comment ID or URL" unless match
match[:comment_id]
end
end
Liquid::Template.register_tag("comment", CommentTag)
# kept for compatibility with existing comments embeds on DEV
Liquid::Template.register_tag("devcomment", CommentTag)
UnifiedEmbed.register(CommentTag, regexp: CommentTag::REGISTRY_REGEXP)

View file

@ -22,7 +22,7 @@ RSpec.describe CommentTag, type: :liquid_tag do
end
it "renders 'Comment Not Found' message if comment ID does not exist" do
liquid = generate_comment_tag("nonexistent ID")
liquid = generate_comment_tag("nonexistentid")
expect(liquid.render).to include("Comment Not Found")
end
@ -52,4 +52,12 @@ RSpec.describe CommentTag, type: :liquid_tag do
expect(liquid.render).to include(user.name)
end
end
context "when given invalid id_code" do
it "raises an error" do
expect do
generate_comment_tag("Invalid%ID").render
end.to raise_error(StandardError, "Invalid Comment ID or URL")
end
end
end

View file

@ -3,7 +3,11 @@ require "rails_helper"
RSpec.describe UnifiedEmbed::Registry do
subject(:unified_embed) { described_class }
let(:user) { create(:user) }
let(:article) { create(:article) }
let(:comment) do
create(:comment, commentable: article, user: user, body_markdown: "TheComment")
end
describe ".find_liquid_tag_for" do
valid_blogcast_url_formats = [
@ -74,6 +78,11 @@ RSpec.describe UnifiedEmbed::Registry do
end
end
it "returns CommentTag for a Forem comment url" do
expect(described_class.find_liquid_tag_for(link: "#{URL.url}/#{user.username}/comment/#{comment.id_code}"))
.to eq(CommentTag)
end
it "returns GistTag for a gist url" do
expect(described_class.find_liquid_tag_for(link: "https://gist.github.com/jeremyf/662585f5c4d22184a6ae133a71bf891a"))
.to eq(GistTag)