Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 24 additions & 3 deletions lib/userializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
module USerializer
NS_SEPARATOR = '::'.freeze

@root_keys = {}
@singular_root_keys = {}

class << self
def serializer_for(obj)
return nil if obj.nil?
Expand All @@ -17,9 +20,27 @@ def serializer_for(obj)
def infered_serializer_class(kls)
return nil if kls.nil?

(kls.name + 'Serializer').split(NS_SEPARATOR).inject(Object) do |o, c|
o.const_get(c)
end
name = "#{kls.name}Serializer"

return Object.const_get(name) if Object.const_defined?(name)

name.split(NS_SEPARATOR).inject(Object) { |o, c| o.const_get(c) }
end

def infered_singular_root_key(kls)
name = kls.name

@singular_root_keys[name] ||= ActiveSupport::Inflector.underscore(
name
).split('/').last.to_sym
end

def infered_root_key(kls)
name = kls.name

@root_keys[name] ||= ActiveSupport::Inflector.pluralize(
ActiveSupport::Inflector.underscore(name).split('/').last
).to_sym
end
end
end
26 changes: 15 additions & 11 deletions lib/userializer/array_serializer.rb
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
require 'oj'
require 'userializer/payload'

module USerializer
class HeterogeneousArray < StandardError; end

class ArraySerializer
def initialize(objs, opts = {}, embed_empty_array: false)
def initialize(objs, opts = {})
@objs = objs.compact
@opts = opts
@meta = opts[:meta]
@embed_empty_array = embed_empty_array
@embed_empty_array = opts[:embed_empty_array] || false

clss = @objs.map(&:class).uniq
obj_class = clss.first
obj_class = @objs.first&.class

raise HeterogeneousArray if clss.count > 1
raise HeterogeneousArray if @objs.any? { |o| !o.instance_of?(obj_class) }

@root_key = opts[:root]&.to_sym
@root_key ||= ActiveSupport::Inflector.pluralize(
ActiveSupport::Inflector.underscore(obj_class.name).split('/').last
).to_sym if obj_class
@root_key ||= USerializer.infered_root_key(obj_class) if obj_class

serializer = opts[:each_serializer]

Expand All @@ -37,14 +35,14 @@ def merge_root(res, opts)
end

def to_hash
res = {}
res = Payload.new

res[@root_key] = [] if @root_key

merge_root(res, @opts)
res[:meta] = @meta if @meta

res
res.to_h
end

def to_json
Expand All @@ -59,7 +57,13 @@ def serializer(obj, opts)
return @serializer.call(obj, opts).new(obj, @opts) if @serializer
return obj.serialize if obj.respond_to?(:serialize)

USerializer.infered_serializer_class(obj.class).new(obj, @opts)
infered_serializer.new(obj, @opts)
end

def infered_serializer
@infered_serializer ||= USerializer.infered_serializer_class(
@objs.first.class
)
end
end
end
12 changes: 9 additions & 3 deletions lib/userializer/attribute.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,23 @@ def initialize(key, opts, block)
@block = block

@skip_nil = opts[:skip_nil] || false
@conditional_block = opts[:if] || proc { true }
@conditional_block = opts[:if]
end

def merge_attributes(res, ser, opts)
return unless @conditional_block.call(ser.object, opts)
return unless allow?(ser, opts)

value = @block ? @block.call(ser.object, opts) : ser.send(@key)
value = @block ? @block.call(ser.object, opts) : ser.read_attribute(@key)

return if value.nil? && @skip_nil

res[@key] = value
end

private

def allow?(ser, opts)
@conditional_block.nil? || @conditional_block.call(ser.object, opts)
end
end
end
98 changes: 70 additions & 28 deletions lib/userializer/base_serializer.rb
Original file line number Diff line number Diff line change
@@ -1,15 +1,37 @@
require 'set'
require 'oj'
require 'active_support/inflector/methods'
require 'userializer/has_one'
require 'userializer/has_many'
require 'userializer/attribute'
require 'userializer/payload'

module USerializer
class BaseSerializer
class << self
def inherited(subclass)
subclass.attrs = self.attrs.dup || { id: Attribute.new(:id, {}, nil) }
subclass.relations = self.relations.dup || {}
subclass.serializer_methods = self.serializer_methods.dup || Set.new
end

# BaseSerializer itself has no registry, so its own methods are never
# treated as serializer methods.
def method_added(name)
super
serializer_methods&.add(name)
end

def include(*mods)
super

mods.each do |mod|
serializer_methods&.merge(
mod.instance_methods + mod.private_instance_methods
)
end

self
end

def attributes(*attrs, &block)
Expand All @@ -33,7 +55,7 @@ def has_many(*attrs)
attrs.each { |attr| @relations[attr] = HasMany.new(attr, opts) }
end

attr_accessor :attrs, :relations
attr_accessor :attrs, :relations, :serializer_methods
end

attr_reader :obj, :meta, :opts
Expand All @@ -44,21 +66,15 @@ def initialize(obj, opts = {})
@obj = obj
@opts = opts
@meta = opts[:meta]
@except = Set.new([opts[:except]].flatten.compact)
@only = Set.new([opts[:only]].flatten.compact)

@root_key = (opts[:root] || ActiveSupport::Inflector.underscore(
obj.class.name
).split('/').last).to_sym
@except = key_filter(opts[:except])
@only = key_filter(opts[:only])
end

def serializable_hash(opts)
res = {}

_attributes.each { |attr| attr.merge_attributes(res, self, opts) }
_relations.each do |rel|
rel.merge_attributes(res, self, opts)
end
_attributes { |attr| attr.merge_attributes(res, self, opts) }
_relations { |rel| rel.merge_attributes(res, self, opts) }

res
end
Expand All @@ -67,28 +83,36 @@ def merge_root(res, key, single, opts)
if single
res[key] = serializable_hash(opts)
else
res[key] ||= []
return if res.include_id?(key, @obj.id)

id = @obj.id

if res[key].detect { |v| id && v[:id] == id }
return
else
res[key] << serializable_hash(opts)
end
res.push(key, serializable_hash(opts))
end

_relations.each { |rel| rel.merge_root(res, self, opts) }
_relations { |rel| rel.merge_root(res, self, opts) }
end

def to_hash
res = {}
res = Payload.new

merge_root(res, @root_key, true, @opts.slice(:scope))
merge_root(res, _root_key, true, @opts.slice(:scope))

res[:meta] = @meta if @meta

res
res.to_h
end

def read_attribute(key)
return send(key) if self.class.serializer_methods.include?(key)

@obj.send(key)
end

def relation_value(key)
@_relation_values ||= {}

return @_relation_values[key] if @_relation_values.key?(key)

@_relation_values[key] = yield
end

def to_json
Expand All @@ -99,20 +123,38 @@ def method_missing(mth); @obj.send(mth); end

private

def _root_key
@_root_key ||= if @opts[:root]
@opts[:root].to_sym
else
USerializer.infered_singular_root_key(@obj.class)
end
end

def _attributes
@_attributes ||= (self.class.attrs || {}).values.select do |attr|
allow?(attr.key)
(self.class.attrs || {}).each_value do |attr|
yield attr if allow?(attr.key)
end
end

def _relations
@_relations ||= (self.class.relations || {}).values.select do |rel|
allow?(rel.key)
(self.class.relations || {}).each_value do |rel|
yield rel if allow?(rel.key)
end
end

def key_filter(keys)
return if keys.nil?

keys = [keys].flatten.compact

Set.new(keys) unless keys.empty?
end

def allow?(key)
return @only.include?(key) if @only.any?
return @only.include?(key) if @only
return true unless @except

!@except.include?(key)
end
end
Expand Down
7 changes: 4 additions & 3 deletions lib/userializer/composite_serializer.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require 'oj'
require 'userializer/payload'

module USerializer
class CompositeObject
Expand Down Expand Up @@ -41,10 +42,10 @@ def merge_root(res, opts)
end

def to_hash
res = {}
res = Payload.new

merge_root(res, @opts)
res
res.to_h
end

def serialize(*_args)
Expand All @@ -64,7 +65,7 @@ def compose_objs(objs)
if obj.is_a?(Hash) || !obj.is_a?(Enumerable)
CompositeObject.new(obj, opts)
else
ArraySerializer.new(obj, opts, embed_empty_array: true)
ArraySerializer.new(obj, opts.merge(embed_empty_array: true))
end
end
end
Expand Down
26 changes: 17 additions & 9 deletions lib/userializer/has_many.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,34 +9,42 @@ def initialize(key, opts)
@ids_key = opts[:ids_key] || build_ids_key(key)

@embed_key = opts[:embed_key] || :id
@conditional_block = opts[:if] || proc { true }
@conditional_block = opts[:if]
end

def merge_attributes(res, ser, opts)
return unless @conditional_block.call(ser.object, opts)
return unless allow?(ser, opts)

res[@ids_key] = (entities(ser) || []).compact.map do |obj|
obj.nil? ? nil : obj.send(@embed_key)
end.compact
res[@ids_key] = (entities(ser) || []).each_with_object([]) do |obj, ids|
id = obj&.send(@embed_key)
ids << id unless id.nil?
end
end

def merge_root(res, ser, opts)
return unless allow?(ser, opts)

objs = entities(ser) || []

return if objs.empty? || !@conditional_block.call(ser.object, opts)
return if objs.empty?

ArraySerializer.new(objs, @opts).merge_root(res, opts)
end

def entities(ser)
obj = ser.send(@key) || []
return obj unless @opts[:scope]
ser.relation_value(@key) do
obj = ser.read_attribute(@key) || []

obj.send(@opts[:scope])
@opts[:scope] ? obj.send(@opts[:scope]) : obj
end
end

private

def allow?(ser, opts)
@conditional_block.nil? || @conditional_block.call(ser.object, opts)
end

def build_ids_key(key)
"#{ActiveSupport::Inflector.singularize(key)}_ids".to_sym
end
Expand Down
Loading
Loading