Alba is a JSON serializer for Ruby, JRuby and TruffleRuby.
Alba is a JSON serializer for Ruby, JRuby and TruffleRuby.
Alba is a JSON serializer for Ruby, JRuby, and TruffleRuby.
Alba allows you to do something like below.
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.
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."
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!
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.
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!
Alba is more feature-rich and pretty fast, too
Gemfile of dreams by Evil Martians
Because it's fast, easy and feature rich!
Alba is faster than most of the alternatives. We have a benchmark.
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.
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.
oj or activesupport while Alba works well with themAlba 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 |
Add this line to your application's Gemfile:
gem 'alba'And then execute:
$ bundle installOr install it yourself as:
$ gem install albaAlba 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.
You can find the documentation on GitHub Pages.
Alba's configuration is fairly simple.
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:
Alba.backend = :ojThis is equivalent as:
Alba.encoder = ->(object) { Oj.dump(object, mode: :strict) }You can also set JSON encoder directly with a Proc.
Alba.encoder = ->(object) { JSON.generate(object) }You can consider setting a backend with Symbol as a shortcut to set encoder.
You can enable the inference feature using the Alba.inflector = SomeInflector API. For example, in a Rails initializer:
Alba.inflector = :active_supportYou can choose which inflector Alba uses for inference. Possible options are:
:active_support for ActiveSupport::Inflector:dry for Dry::InflectorTo disable inference, set the inflector to nil:
Alba.inflector = nilTo check if inference is enabled etc, inspect the return value of inflector:
if Alba.inflector.nil?
puts 'inflector not set'
else
puts "inflector is set to #{Alba.inflector}"
endYou can set the default superclass for resource classes created for Nested Attributes and Traits.
Alba.default_superclass = MyBaseSerializerNote that in some environments like Rails applications, the class object is not loaded in the initializer phase. You can also set String.
Alba.default_superclass = 'MyBaseSerializer'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.
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.
# 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
endThis even works with users collection.
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:
class UserResource
include Alba::Resource
attribute :some_other_name, &:name
endConsider following code:
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).serializeBy 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.
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.
class Foo
def bar
'This is Foo'
end
end
class FooResoNo open issues yet, or sync has not completed.