Class: TinySerializer

Inherits:
Object
  • Object
show all
Extended by:
DSL
Includes:
RailsExtensions
Defined in:
lib/tiny_serializer.rb,
lib/tiny_serializer/dsl.rb,
lib/tiny_serializer/version.rb,
lib/tiny_serializer/rails_extensions.rb

Overview

Simple DSL for converting objects to Hashes, which is mostly API-compatible with ActiveModel::Serializer. The Hashes can be rendered as JSON by Rails.

I have also added some fast_jsonapi API parameters that do nothing, to ease later transition to that library.

Usage

# my_object.rb
MyObject = Struct.new(:id, :first_name, :last_name, :date) do
  def parent; nil; end
  def sub_record; nil; end
  def related_items; []; end
end

# my_object_serializer.rb
class MyObjectSerializer < TinySerializer
  attributes :id,
             :first_name,
             :last_name,
             :date

  belongs_to :parent, serializer: ParentSerializer
  has_one :sub_record # serializer will be inferred to be SubRecordSerializer
  has_many :related_items, serializer: RelatedItemSerializer

  attribute :full_name do
    "#{object.first_name} #{object.last_name}"
  end
end

# my_objects_controller.rb
def show
  @my_object = MyObject.new(1, "Fred", "Flintstone", Date.new(2000, 1, 1))
  render json: MyObjectSerializer.new(@my_object).serialize
end

RailsExtensions

The RailsExtensions module is automatically prepended when TinySerializer is used in a Rails app. It defines some small convenience instance methods.

Defined Under Namespace

Modules: DSL, RailsExtensions

Constant Summary collapse

VERSION =
"2.1.1"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from DSL

_initialize_attributes, _is_id?, _is_serializer?, attribute, attribute_names, attributes, belongs_to, collection, collection_names, collections, has_many, has_one, sub_record, sub_record_names, sub_records

Methods included from RailsExtensions

#url_helpers

Constructor Details

#initialize(object, options = {}) ⇒ TinySerializer

Create a new serializer instance.

object

The object to serialize. Can be a single object or a collection of objects.



76
77
78
79
# File 'lib/tiny_serializer.rb', line 76

def initialize(object, options = {})
  @object = object
  @options = options
end

Instance Attribute Details

#loggerObject

Optional logger object. Defaults to Rails.logger in a Rails app.



69
70
71
# File 'lib/tiny_serializer.rb', line 69

def logger
  @logger
end

#objectObject

The object to serialize as a Hash



63
64
65
# File 'lib/tiny_serializer.rb', line 63

def object
  @object
end

#optionsObject

Hash of data to be passed to blocks



66
67
68
# File 'lib/tiny_serializer.rb', line 66

def options
  @options
end

Class Method Details

.is_collection?(object) ⇒ Boolean

Check if #object is a collection.

Returns:

  • (Boolean)


136
137
138
# File 'lib/tiny_serializer.rb', line 136

def is_collection?(object)
  object.respond_to?(:each) && !object.respond_to?(:each_pair)
end

.serialize(object, options = {}) ⇒ Object

The same as:

TinySerializer.new(object).serializable_hash


124
125
126
# File 'lib/tiny_serializer.rb', line 124

def serialize(object, options = {})
  new(object, options).serializable_hash
end

.serialize_each(collection) ⇒ Object

Same as #serialize, but raises ArgumentError if ‘collection` doesn’t appear to be a collection.

Raises:

  • (ArgumentError)


130
131
132
133
# File 'lib/tiny_serializer.rb', line 130

def serialize_each(collection)
  raise ArgumentError, "collection does not appear to be a collection" unless is_collection?(collection)
  new(collection).serializable_hash
end

Instance Method Details

#as_json(_ = nil) ⇒ Object

Serialize #object as a Hash, then call #as_json on the Hash, which will convert keys to Strings.

There shouldn’t be a need to call this, but we implement it to fully support ActiveSupport’s magic JSON protocols.



101
102
103
# File 'lib/tiny_serializer.rb', line 101

def as_json(_ = nil)
  serializable_hash.as_json
end

#collection?Boolean

Return true if #object is a collection.

Returns:

  • (Boolean)


115
116
117
# File 'lib/tiny_serializer.rb', line 115

def collection?
  self.class.is_collection?(@object)
end

#serializable_hash(_ = nil) ⇒ Object Also known as: to_hash, serialize

Serialize #object as a Hash with Symbol keys. Returns nil if #object is nil.



83
84
85
86
87
88
89
90
91
# File 'lib/tiny_serializer.rb', line 83

def serializable_hash(_ = nil)
  return serialize_single_object_to_hash unless collection?

  json = []
  @object.each do |object|
    json << self.class.new(object, @options).serializable_hash
  end
  json
end

#to_json(_ = nil) ⇒ Object

Serialize #object to a JSON String.

Calls #serializable_hash, then call #to_json on the resulting Hash, converting it to a String using the automatic facilities for doing so from ActiveSupport.



110
111
112
# File 'lib/tiny_serializer.rb', line 110

def to_json(_ = nil)
  serializable_hash.to_json
end