module BrightSerializer::Serializer

Constants

DEFAULT_OJ_OPTIONS
SUPPORTED_TRANSFORMATION

Public Class Methods

included(base) click to toggle source
Calls superclass method
# File lib/bright_serializer/serializer.rb, line 14
def self.included(base)
  super
  base.extend ClassMethods
  base.instance_variable_set(:@attributes_to_serialize, [])
end
new(object, **options) click to toggle source
# File lib/bright_serializer/serializer.rb, line 20
def initialize(object, **options)
  @object = object
  @params = options.delete(:params)
  @fields = Set.new(options.delete(:fields))
end

Public Instance Methods

serializable_hash() click to toggle source
# File lib/bright_serializer/serializer.rb, line 35
def serializable_hash
  if @object.respond_to?(:each) && !@object.respond_to?(:each_pair)
    @object.map { |o| serialize o }
  else
    serialize(@object)
  end
end
Also aliased as: to_hash
serializable_json(*_args) click to toggle source
# File lib/bright_serializer/serializer.rb, line 45
def serializable_json(*_args)
  ::Oj.dump(to_hash, DEFAULT_OJ_OPTIONS)
end
Also aliased as: to_json
serialize(object) click to toggle source
# File lib/bright_serializer/serializer.rb, line 26
def serialize(object)
  self.class.attributes_to_serialize.each_with_object({}) do |attribute, result|
    next if @fields.any? && !@fields.include?(attribute.key)
    next unless attribute.condition?(object, @params)

    result[attribute.transformed_key] = attribute.serialize(object, @params)
  end
end
to_hash()
Alias for: serializable_hash
to_json(*_args)
Alias for: serializable_json