DEV: Option to preload category custom fields for site serializer

This commit is contained in:
Vinoth Kannan 2019-03-16 17:18:57 +05:30
parent bc488c8dc0
commit 4477938ea7
5 changed files with 52 additions and 1 deletions

View File

@ -5,8 +5,12 @@ require_dependency 'trust_level'
class Site
include ActiveModel::Serialization
cattr_accessor :preloaded_category_custom_fields
self.preloaded_category_custom_fields = Set.new
def initialize(guardian)
@guardian = guardian
Category.preload_custom_fields(categories, preloaded_category_custom_fields) if preloaded_category_custom_fields.present?
end
def site_setting

View File

@ -26,7 +26,8 @@ class BasicCategorySerializer < ApplicationSerializer
:subcategory_list_style,
:default_top_period,
:minimum_required_tags,
:navigate_to_first_post_after_read
:navigate_to_first_post_after_read,
:custom_fields
has_one :uploaded_logo, embed: :object, serializer: CategoryUploadSerializer
has_one :uploaded_background, embed: :object, serializer: CategoryUploadSerializer
@ -54,4 +55,12 @@ class BasicCategorySerializer < ApplicationSerializer
def notification_level
object.notification_level
end
def custom_fields
object.preloaded_custom_fields
end
def include_custom_fields?
custom_fields.present?
end
end

View File

@ -97,4 +97,8 @@ class CategorySerializer < BasicCategorySerializer
def allowed_tag_groups
object.tag_groups.pluck(:name)
end
def custom_fields
object.custom_fields
end
end

View File

@ -0,0 +1,14 @@
require 'rails_helper'
require_dependency 'category'
describe CategorySerializer do
let(:category) { Fabricate(:category) }
it "includes custom fields" do
category.custom_fields["enable_marketplace"] = true
category.save_custom_fields
json = described_class.new(category, scope: Guardian.new, root: false).as_json
expect(json[:custom_fields]).to be_present
end
end

View File

@ -0,0 +1,20 @@
require 'rails_helper'
require_dependency 'site'
describe SiteSerializer do
let(:guardian) { Guardian.new }
it "includes category custom fields only if its preloaded" do
category = Fabricate(:category)
category.custom_fields["enable_marketplace"] = true
category.save_custom_fields
data = MultiJson.dump(described_class.new(Site.new(guardian), scope: guardian, root: false))
expect(data).not_to include("enable_marketplace")
Site.preloaded_category_custom_fields << "enable_marketplace"
data = MultiJson.dump(described_class.new(Site.new(guardian), scope: guardian, root: false))
expect(data).to include("enable_marketplace")
end
end