Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

alba

> 数据库
Open source

Alba is a JSON serializer for Ruby, JRuby and TruffleRuby.

1.2K stars0 likes1 views
WebsiteGitHub

About

Alba is a JSON serializer for Ruby, JRuby and TruffleRuby.


Alba

Alba is a JSON serializer for Ruby, JRuby, and TruffleRuby.

TL;DR

Alba allows you to do something like below.

ruby
class User
  attr_accessor :id, :name, :email

  def initialize(id, name, email)
    @id = id
    @name = name
    @email = email
  end
end

class UserResource
  include Alba::Resource

  root_key :user

  attributes :id, :name

  attribute :name_with_email do |resource|
    "#{resource.name}: #{resource.email}"
  end
end

user = User.new(1, 'Masafumi OKURA', '[email protected]')
UserResource.new(user).serialize
# => '{"user":{"id":1,"name":"Masafumi OKURA","name_with_email":"Masafumi OKURA: masafumi@example.com"}}'

Seems useful? Continue reading!

Pro tip: You can find more examples in separate Ruby files under "examples" directory.

Coming from ActiveModelSerializers(AMS)?

If you are using ActiveModelSerializers and interested in Alba, we have an automatic converter! alba_migration gem from ShoheiMitani "provides a command-line tool to convert AMS serializer classes to Alba resource classes, making your migration process easier and less error-prone."

Discussions

Alba uses GitHub Discussions to openly discuss the project.

If you've already used Alba, please consider posting your thoughts and feelings on Feedback. The fact that you enjoy using Alba gives me energy to keep developing Alba!

If you have feature requests or interesting ideas, join us with Ideas. Let's make Alba even better, together!

Resources

If you want to know more about Alba, there's a screencast created by Sebastian from Hanami Mastery. It covers basic features of Alba and how to use it in Hanami.

What users say about Alba

Alba is a well-maintained JSON serialization engine, for Ruby, JRuby, and TruffleRuby implementations, and what I like in this gem - except of its speed, is the easiness of use, no dependencies and the fact it plays well with any Ruby application!

Hanami Mastery by Seb Wilgosz

Alba is more feature-rich and pretty fast, too

Gemfile of dreams by Evil Martians

Why Alba?

Because it's fast, easy and feature rich!

Fast

Alba is faster than most of the alternatives. We have a benchmark.

Easy

Alba is easy to use because there are only a few methods to remember. It's also easy to understand due to clean and small codebase. Finally it's easy to extend since it provides some methods for override to change default behavior of Alba.

Feature rich

While Alba's core is simple, it provides additional features when you need them. For example, Alba provides a way to control circular associations, root key and association resource name inference and supports layouts.

Other reasons

  • Dependency free, no need to install oj or activesupport while Alba works well with them
  • Well tested, the test coverage is 99%
  • Well maintained, getting frequent update and new releases (see version history)

Comparison with other serializers

Alba aims to provide a well-balanced combination of simplicity, performance, and features. Here's how it compares to other popular Ruby JSON serializers:

Feature Alba AMS Blueprinter JSONAPI::Serializer JBuilder
Dependencies None ActiveSupport Minimal Minimal Rails
JSON:API Compliance Manual Planned Via extension Full support Manual
Caching Not built-in Yes Via extension Supported Fragment caching
Key Transformation Yes Yes Yes Yes Yes
Conditional Attributes Yes Yes Yes Yes Yes
Type Validation & Coercion Yes No No No No
Custom Type System Yes No No No No
Nested Attributes Yes No No No Partial
Circular Reference Control Yes with within Limited No No No
Error Handling Strategies Flexible Limited Limited Basic Basic
Nil Handling Yes No No No No
Layout System Yes No No No No
Maintenance Status Active Minimal Active Active Active

Installation

Add this line to your application's Gemfile:

ruby
gem 'alba'

And then execute:

$ bundle install

Or install it yourself as:

$ gem install alba

Supported Ruby versions

Alba works with CRuby 3.0 and higher and latest JRuby and TruffleRuby. However, Ruby 3.0 is not actively tested, so use it at your own risk.

Documentation

You can find the documentation on GitHub Pages.

Features

  • Conditional attributes and associations
  • Selectable backend
  • Key transformation
  • Root key and association resource name inference
  • Inline definition without explicit classes
  • Error handling
  • Nil handling
  • Circular associations control
  • Types for validation and conversion
  • Layout
  • No runtime dependencies

Usage

Configuration

Alba's configuration is fairly simple.

Backend configuration

Backend is the actual part serializing an object into JSON. Alba supports these backends.

name description requires_external_gem encoder
oj, oj_strict Using Oj in strict mode Yes(C extension) Oj.dump(object, mode: :strict)
oj_rails It's oj but in rails mode Yes(C extension) Oj.dump(object, mode: :rails)
oj_default It's oj but respects mode set by users Yes(C extension) Oj.dump(object)
active_support For Rails compatibility Yes ActiveSupport::JSON.encode(object)
default, json Using json gem No JSON.generate(object)

You can set a backend like this:

ruby
Alba.backend = :oj

This is equivalent as:

ruby
Alba.encoder = ->(object) { Oj.dump(object, mode: :strict) }

Encoder configuration

You can also set JSON encoder directly with a Proc.

ruby
Alba.encoder = ->(object) { JSON.generate(object) }

You can consider setting a backend with Symbol as a shortcut to set encoder.

Inference configuration

You can enable the inference feature using the Alba.inflector = SomeInflector API. For example, in a Rails initializer:

ruby
Alba.inflector = :active_support

You can choose which inflector Alba uses for inference. Possible options are:

  • :active_support for ActiveSupport::Inflector
  • :dry for Dry::Inflector
  • any object which conforms to the protocol (see below)

To disable inference, set the inflector to nil:

ruby
Alba.inflector = nil

To check if inference is enabled etc, inspect the return value of inflector:

ruby
if Alba.inflector.nil?
  puts 'inflector not set'
else
  puts "inflector is set to #{Alba.inflector}"
end

Default superclass configuration

You can set the default superclass for resource classes created for Nested Attributes and Traits.

ruby
Alba.default_superclass = MyBaseSerializer

Note that in some environments like Rails applications, the class object is not loaded in the initializer phase. You can also set String.

ruby
Alba.default_superclass = 'MyBaseSerializer'

Naming

Alba tries to infer resource name from class name like the following.

Class name Resource name
FooResource Foo
FooSerializer Foo
FooElse FooElse

Resource name is used as the default name of the root key, so you might want to name it ending with "Resource" or "Serializer"

When you use Alba with Rails, it's recommended to put your resource/serializer classes in corresponding directory such as app/resources or app/serializers.

Simple serialization with root key

You can define attributes with (yes) attributes macro with attribute names. If your attribute need some calculations, you can use attribute with block.

…

You can define instance methods on resources so that you can use it as attribute name in attributes.

ruby
# The serialization result is the same as above
class UserResource
  include Alba::Resource

  root_key :user, :users # Later is for plural

  attributes :id, :name, :name_with_email

  # Attribute methods must accept one argument for each serialized object
  def name_with_email(user)
    "#{user.name}: #{user.email}"
  end
end

This even works with users collection.

ruby
user1 = User.new(1, 'Masafumi OKURA', '[email protected]')
user2 = User.new(2, 'Test User', '[email protected]')
UserResource.new([user1, user2]).serialize
# => '{"users":[{"id":1,"name":"Masafumi OKURA","name_with_email":"Masafumi OKURA: masafumi@example.com"},{"id":2,"name":"Test User","name_with_email":"Test User: test@example.com"}]}'

If you have a simple case where you want to change only the name, you can use the Symbol to Proc shortcut:

ruby
class UserResource
  include Alba::Resource

  attribute :some_other_name, &:name
end

Methods conflict

Consider following code:

ruby
class Foo
  def bar
    'This is Foo'
  end
end

class FooResource
  include Alba::Resource

  attributes :bar

  def bar
    'This is FooResource'
  end
end

FooResource.new(Foo.new).serialize

By default, Alba creates the JSON as '{"bar":"This is FooResource"}'. This means Alba calls a method on a Resource class and doesn't call a method on a target object. This rule is applied to methods that are explicitly defined on Resource class, so methods that Resource class inherits from Object class such as format are ignored.

ruby
class Foo
  def format
    'This is Foo'
  end
end

class FooResource
  include Alba::Resource

  attributes :format

  # Here, `format` method is available
end

FooResource.new(Foo.new).serialize
# => '{"bar":"This is Foo"}'

If you'd like Alba to call methods on a target object, use prefer_object_method! like below.

ruby
class Foo
  def bar
    'This is Foo'
  end
end

class FooReso

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyhacktoberfestjsonjson-serializationjson-serializer

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库