module Serega::InstanceMethods
Instance methods of serializers. An instance keeps its field selection and serializes many times.
Public Class Methods
(?only: fields?, ?with: fields?, ?except: fields?, ?check_initiate_params: bool?) → void
Source
# File lib/serega.rb, line 619 def initialize(only: nil, with: nil, except: nil, check_initiate_params: nil) @plan = self.class.plan_cache.fetch(only, with, except, check_initiate_params: check_initiate_params) @direct_hash_builder = @plan.direct_hash_builder end
Prepares a serializer with a field selection. The options are the field options of Serega::ClassMethods#to_h.
serializer = UserSerializer.new(only: [:first_name]) serializer.to_h(user) # => {first_name: "Bruce"} serializer.to_h(users) # => [{first_name: "Bruce"}, {first_name: "Alfred"}]
Public Instance Methods
(untyped object, ?context: context?, ?many: bool?) → untyped
Source
# File lib/serega.rb, line 639 def call(object, context: nil, many: nil) # One Hash source of a flat plan skips #serialize_to and the run: 73 ns # and 1 object instead of 136 ns and 3 objects (Ruby 4.0, YJIT). builder = @direct_hash_builder if builder && object && !many && (context.nil? || context.is_a?(Hash)) many = SeregaUtils::CollectionDetector.call(object, @plan.collection_classes) if many.nil? return builder.call_one(object, context.nil? ? FROZEN_EMPTY_HASH : context) unless many end serialize_to(:hash, object, context, many, FROZEN_EMPTY_HASH) end
Serializes an object or a list to a Hash or an Array of Hashes, with the serialization options of Serega::ClassMethods#to_h
UserSerializer.new.to_h(user, context: {admin: true})
Also aliased as: to_h
(untyped object, ?context: context?, ?many: bool?) → untyped
Source
# File lib/serega.rb, line 659 def to_data(object, context: nil, many: nil) serialize_to(:data, object, context, many, FROZEN_EMPTY_HASH) end
Serializes like to_h, to Data objects
(untyped object, ?context: context?, ?many: bool?) → String
Source
# File lib/serega.rb, line 680 def to_json(object, context: nil, many: nil) JSON.generate(call(object, context: context, many: many)) end
(untyped object, ?context: context?, ?many: bool?) → untyped
Source
# File lib/serega.rb, line 669 def to_struct(object, context: nil, many: nil) serialize_to(:struct, object, context, many, FROZEN_EMPTY_HASH) end
Serializes like to_h, to Struct objects