Sha256: 9a922c3144414abaeaf4b539c1b3690aa8039acca73fc15fd89e169398291a0b
Contents?: true
Size: 1.31 KB
Versions: 1
Compression:
Stored size: 1.31 KB
Contents
# frozen_string_literal: true module AdequateSerialization # With this module, you can define serializers inline in the object that # they're serializing. You use it with the `AdequateSerialization::inline` # method to define the serializer dynamically, as in: # # class User # attr_reader :id, :name, :title # # def initialize(id:, name:, title: nil) # @id = id # @name = name # @title = title # end # # include AdequateSerialization.inline { # attribute :id, :name # attribute :title, optional: true # } # end # # user = User.new(id: 1, name: 'Clark Kent') # user.as_json # # => {:id=>1, :name=>"Clark Kent"} # # user = User.new(id: 2, name: 'Diana Prince', title: 'Wonder Woman') # user.as_json(includes: :title) # # => {:id=>1, :name=>"Diana Prince", :title=>"Wonder Woman"} class InlineSerializer < Module attr_reader :block def initialize(&block) @block = block end def included(base) base.include(Serializable) # No need to memoize within the method because the block will hold on to # local variables for us. serializer = Class.new(Serializer, &block).new base.define_singleton_method(:serializer) { serializer } end end def self.inline(&block) InlineSerializer.new(&block) end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
adequate_serialization-1.0.0 | lib/adequate_serialization/inline_serializer.rb |