A platform for community discussion. Free, open, simple.
DEV: Allow plugins to register Onebox handlers (#16870)
Bianca Nenciu6c8f491dc3af
diff --git a/lib/inline_oneboxer.rb b/lib/inline_oneboxer.rbindex 30e381875d6..22bf4762378 100644--- a/lib/inline_oneboxer.rb+++ b/lib/inline_oneboxer.rb@@ -21,6 +21,14 @@ class InlineOneboxerDiscourse.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 topicreturn nilend+ elsif handler = local_handlers[route[:controller]]+ return handler.call(url, route)endenddiff --git a/lib/oneboxer.rb b/lib/oneboxer.rbindex d21d940c494..d1c147941bb 100644--- a/lib/oneboxer.rb+++ b/lib/oneboxer.rb@@ -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 Oneboxerwhen "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)+ endendhtml = html.presence || "<a href='#{URI(url).to_s}'>#{URI(url).to_s}</a>"diff --git a/spec/lib/inline_oneboxer_spec.rb b/spec/lib/inline_oneboxer_spec.rbindex 1e84076b72d..10dcb4b607b 100644--- a/spec/lib/inline_oneboxer_spec.rb+++ b/spec/lib/inline_oneboxer_spec.rb@@ -314,4 +314,18 @@ describe InlineOneboxer doendendend++ 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+ endenddiff --git a/spec/lib/oneboxer_spec.rb b/spec/lib/oneboxer_spec.rbindex 56c90495ac7..d1411b14619 100644--- a/spec/lib/oneboxer_spec.rb+++ b/spec/lib/oneboxer_spec.rb@@ -641,4 +641,14 @@ describe Oneboxer doendend+ 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+ endend