DEV: Allow plugins to register Onebox handlers (#16870)

This targets only the local Oneboxes and allows plugins to customize
regular or inline Oneboxes for routes inside the site.
This commit is contained in:
Bianca Nenciu 2022-05-23 20:02:02 +03:00 committed by GitHub
parent 28573b504f
commit 6c8f491dc3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 46 additions and 0 deletions

View File

@ -21,6 +21,14 @@ class InlineOneboxer
Discourse.cache.read(cache_key(url))
end
def self.local_handlers
@local_handlers ||= {}
end
def self.register_local_handler(controller, &handler)
local_handlers[controller] = handler
end
def self.lookup(url, opts = nil)
opts ||= {}
opts = opts.with_indifferent_access
@ -46,6 +54,8 @@ class InlineOneboxer
# not permitted to see topic
return nil
end
elsif handler = local_handlers[route[:controller]]
return handler.call(url, route)
end
end

View File

@ -48,6 +48,14 @@ module Oneboxer
@allowed_post_types ||= [Post.types[:regular], Post.types[:moderator_action]]
end
def self.local_handlers
@local_handlers ||= {}
end
def self.register_local_handler(controller, &handler)
local_handlers[controller] = handler
end
def self.preview(url, options = nil)
options ||= {}
invalidate(url) if options[:invalidate_oneboxes]
@ -248,6 +256,10 @@ module Oneboxer
when "topics" then local_topic_html(url, route, opts)
when "users" then local_user_html(url, route)
when "list" then local_category_html(url, route)
else
if handler = local_handlers[route[:controller]]
handler.call(url, route)
end
end
html = html.presence || "<a href='#{URI(url).to_s}'>#{URI(url).to_s}</a>"

View File

@ -314,4 +314,18 @@ describe InlineOneboxer do
end
end
end
context "register_local_handler" do
it "calls registered local handler" do
InlineOneboxer.register_local_handler('wizard') do |url, route|
{ url: url, title: 'Custom Onebox for Wizard' }
end
url = "#{Discourse.base_url}/wizard"
results = InlineOneboxer.new([url], skip_cache: true).process
expect(results).to be_present
expect(results[0][:url]).to eq(url)
expect(results[0][:title]).to eq('Custom Onebox for Wizard')
end
end
end

View File

@ -641,4 +641,14 @@ describe Oneboxer do
end
end
context "register_local_handler" do
it "calls registered local handler" do
Oneboxer.register_local_handler('wizard') do |url, route|
'Custom Onebox for Wizard'
end
url = "#{Discourse.base_url}/wizard"
expect(Oneboxer.preview(url)).to eq('Custom Onebox for Wizard')
end
end
end