• Stars
    star
    107
  • Rank 312,286 (Top 7 %)
  • Language
    Ruby
  • Created over 8 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Plain old Ruby for generating primitive data structures from object graphs.

Serial

Build Status Dependency Status Code Climate Gem Version Inline docs

Psst, full documentation can be found at rubydoc.info/gems/serial

Serial is a light-weight and simple serialization library. Its primary purpose is to generate primitive datastructures from object graphs, in other words to help you serialize your data.

Serial is sponsored by Elabs.

elabs logo

Installation

Add this line to your application's Gemfile:

gem "serial"

And then execute:

$ bundle

The DSL

Full reference: Serial::HashBuilder, Serial::ArrayBuilder.

  • All keys are turned into strings.
  • There is no automatic camel-casing. You name your keys the way you want them.
  • Using the same key twice will raise an error by default.
  • To override the value for an existing key, use the respective !-method DSL, i.e. #attribute!, #collection!, #map!, or #merge!.

Simple attributes

#attribute creates a simple attribute with a value.

ProjectSerializer = Serial::Serializer.new do |h, project|
  h.attribute(:id, project.id)
  h.attribute(:displayName, project.display_name)
end # => { "id" => …, "displayName" => … }

Nested attributes

#attribute supports nesting by giving it a block.

ProjectSerializer = Serial::Serializer.new do |h, project|
  h.attribute(:owner, project.owner) do |h, owner|
    h.attribute(:name, owner.name)
  end
end # => { "owner" => { "name" => … } }

Collections

#map is a convenient method for serializing lists of items.

ProjectSerializer = Serial::Serializer.new do |h, project|
  h.map(:assignments, project.assignments) do |h, assignment|
    h.attribute(:id, assignment.id)
    h.attribute(:duration, assignment.duration)
  end
end # => { "assignments" => [{ "id" => …, "duration" => … }, …] }

The low-level interface powering #map is #collection.

ProjectSerializer = Serial::Serializer.new do |h, project|
  h.collection(:indices) do |l|
    l.element { |h| h.attribute(…)  }
    l.element { |h| h.attribute(…)  }

    l.collection do |l|
      l.element { … }
      l.element { … }
    end
  end
end # => { "indices" => [{…}, {…}, [{…}, {…}]] }

Merging

#merge will let you merge another serializer without introducing a new nesting level.

ProjectSerializer = Serial::Serializer.new do |h, project|
  h.attribute(:name, project.name)
end # => { "name" => … }

FullProjectSerializer = Serial::Serializer.new do |h, project|
  h.merge(project, &ProjectSerializer)
  h.attribute(:description, project.description)
end # { "name" => …, "description" => … }

Composition

You can compose serializers by passing them as blocks to the DSL methods.

PersonSerializer = Serial::Serializer.new do |h, person|
  h.attribute(:name, person.name)
end # => { "name" => … }

ProjectSerializer = Serial::Serializer.new do |h, project|
  h.attribute(:owner, project.owner, &PersonSerializer)
  h.map(:people, project.people, &PersonSerializer)
end # { "owner" => { "name" => … }, "people" => [{ "name" => … }, …] }

Using your serializers

Full reference: Serial::Serializer.

  • The context parameter in the below examples (when using #call and #map) is optional, if not provided regular block scoping rules apply.
  • Tip: include Serial::RailsHelpers in ApplicationController for a convenient #serialize method.

Serializing a single object

project = Project.find(…)
context = self
ProjectSerializer.call(context, project) # => { … }

Serializing a list of objects

projects = Project.all
context = self
ProjectSerializer.map(context, projects) # => [{ … }, …]

Using with Rails

# app/serializers/project_serializer.rb
ProjectSerializer = Serial::Serializer.new do |h, project|
  …
end
# app/controllers/project_controller.rb
class ProjectController < ApplicationController
  include Serial::RailsHelpers

  def show
    project = Project.find(…)

    # 1. Using helper from RailsHelpers.
    render json: serialize(project)

    # 2. Explicitly mentioning serializer using helper method.
    render json: serialize(project, &ProjectSerializer)

    # 3. Explicitly mentioning serializer.
    render json: ProjectSerializer.call(self, project)
  end
end

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/elabs/serial. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

More Repositories

1

pundit

Minimal authorization through OO design and pure Ruby classes
Ruby
8,143
star
2

serenade.js

Client side MVC framework
CoffeeScript
525
star
3

godmin

Admin framework for Rails 5+
Ruby
486
star
4

mobile-websocket-example

Mobile websocket example
Objective-C
387
star
5

BarcodeReaderSample

A barcode scanner example using Google Play services.
Java
68
star
6

econfig

Flexible configuration for Ruby applications
Ruby
68
star
7

christmas_tree_formatter

Ruby
35
star
8

tiny-autocomplete

A small and snappy (2k minified+gzipped!) JavaScript autocomplete plugin for Zepto and jQuery
JavaScript
34
star
9

elabs_matchers

A collection of useful RSpec matchers
Ruby
29
star
10

ar_outer_joins

Adds outer_joins to ActiveRecord so you can outer join
Ruby
25
star
11

nanomachine

A really tiny state machine for ruby. No events, only acceptable transitions and transition callbacks.
Ruby
19
star
12

docker_deploy

Deploy dockerized applications via Rake
Ruby
16
star
13

tolken

A down-to-earth database translation Gem for Rails using psql jsonb
Ruby
15
star
14

stompede

Ruby Pub/Sub server using the STOMP protocol, built on Celluloid
Ruby
15
star
15

sun_time

Calculate the time of sunrise and sunset for location on a specific date
Ruby
14
star
16

scavenger

Scavenger: a Rails plugin for generating SVG sprite sheets
Ruby
10
star
17

middleman-scavenger

A middleman extension for automatically creating SVG sprite sheets
Ruby
8
star
18

serenade.rb

Serenade.js for Ruby, Rails, and Sprockets
JavaScript
8
star
19

serenade_rails

Use Serenade.js from the asset pipeline
JavaScript
8
star
20

KotlinWithVolley

Kotlin
6
star
21

jquery.autocomplete.tokenized

A simple jQuery plugin for autocomplete, with tokenization support.
JavaScript
6
star
22

dominion.js

Simplify and beautify the DOM api
JavaScript
6
star
23

cors

[DEPRECATED] CORS policy validation- and signing library for Amazon S3 REST API, and (in the future) Filepicker.io security signatures.
Ruby
6
star
24

phoenix-aws-auto-scaling

Elixir
5
star
25

serenade.service.js

Extension to serenade to facilitate mapping models to server resources
CoffeeScript
5
star
26

econfig-keychain

An OSX keychain adapter for Econfig.
Ruby
4
star
27

gcm4ex

https://github.com/chvanikoff/apns4ex but for GCM
Elixir
3
star
28

DynamicStackView

A lightweight, smarter UIStackView.
Swift
3
star
29

FlowControllerKit

Making FlowControllers smoother
Swift
3
star
30

front_end_testing_talk

Our presentation "The Front End Testing Frontier" given by cjkihlbom and jnicklas at Scottish Ruby Conference 2011.
JavaScript
3
star
31

corsair

A Rack middleware for injecting CORS headers into responses
Ruby
2
star
32

trusted_attributes

Mass assignment protection in Rails controllers
Ruby
2
star
33

genpw

Very simple bash password generator
Shell
2
star
34

stomp_parser

Fast STOMP parser for Ruby
Ruby
2
star
35

varvet

Ruby
2
star
36

broccoli-requirejs

Run a Broccoli tree through the r.js optimized
JavaScript
2
star
37

safebox

Simple encryption of secrets using RbNaCl.
Ruby
1
star
38

godmin-activestorage

A Godmin plugin to upload and attach files via Active Storage
Ruby
1
star
39

ELStompClient

Objective-C STOMP client.
Objective-C
1
star
40

broccoli-serenade

Broccoli filter which compiles Serenade.js views
JavaScript
1
star
41

freegeoip-rails

Rails engine with IP geolocation API like Freegeoip
Ruby
1
star
42

godmin-uploads

Ruby
1
star
43

charterer

An application for tagging and viewing statistics about your Instagram feed
Ruby
1
star
44

github-versions

Ruby
1
star
45

middleman_mynewsdesk

A Middleman plugin for Mynewsdesk press releases
Ruby
1
star
46

godmin-tags

Ruby
1
star
47

tagliatelle

Tiny library for tagging content
Ruby
1
star
48

content-cli

JavaScript
1
star
49

css-sense

A VS Code plugin for autocompleting CSS classnames in React and TypeScript
JavaScript
1
star
50

phttp

Make parallel requests with Typhoeus via promises
Ruby
1
star
51

broccoli-eco

Compile ECO templates with Broccoli
JavaScript
1
star
52

scoped-search

Easily implement search forms and column ordering based on your models scopes
Ruby
1
star
53

pagelab

A simple wiki engine built with Ruby on Rails
Ruby
1
star