Mutils
Mutils is a general-purpose helper gem for Ruby and Rails apps. Serialization is one supported feature today, with room for more reusable utilities over time.
Today, Mutils primarily provides a class-based serialization API for turning Ruby objects into predictable hashes or JSON.
What it provides
- attribute declarations for model fields
- computed serializer methods
- block-based fields with access to
params has_many,has_one, andbelongs_torelationships- conditional inclusion with
if: proc - selective field loading with
includes: - optional JSON root keys with
name_tag - a Rails generator for serializer scaffolding
Quick start
gem "mutils"
bundle install
class UserSerializer < Mutils::Serialization::BaseSerializer
attributes :id, :first_name, :last_name
custom_methods :full_name
def full_name
"#{scope.first_name} #{scope.last_name}"
end
end
UserSerializer.new(user).to_h
# => { id: 1, first_name: "Ada", last_name: "Lovelace", full_name: "Ada Lovelace" }
Core ideas
attributesare always included by defaultattributeis opt-in by default unlessalways_include: truecustom_methodsare always included by defaultcustom_methodis opt-in by default unlessalways_include: true- relationships are opt-in by default unless
always_include: true
That split is intentional: bulk declarations default to “include now”, while single declarations are useful for optional fields.