Skip to content

Syati/structured_params

Repository files navigation

StructuredParams

English | 日本語

Type-safe API parameter validation and form objects for Rails

StructuredParams solves these challenges:

  • API endpoints: Type checking, validation, and automatic casting of request parameters
  • Form objects: Validation and conversion of complex form inputs to models

Built on ActiveModel, making nested objects and arrays easy to handle.

Key Features

  • API Parameter Validation - Type-safe request validation
  • Form Objects - Encapsulate complex form logic
  • Nested Structure Support - Automatic casting for objects and arrays
  • Strong Parameters Integration - Auto-generate permit lists
  • ActiveModel Compatible - Support for validations, serialization, and other standard features
  • RBS Type Definitions - Type-safe development experience

Quick Start

# Installation
gem 'structured_params'

# Initialize
StructuredParams.register_types

1. API Parameter Validation

class UserParams < StructuredParams::Params
  attribute :name, :string
  attribute :age, :integer
  
  validates :name, presence: true
  validates :age, numericality: { greater_than: 0 }
end

# Use in API controller
def create
  permitted = UserParams.permit(params, require: false)
  user_params = UserParams.new(permitted)
  
  if user_params.valid?
    User.create!(user_params.attributes)
  else
    render json: { errors: user_params.errors }, status: :unprocessable_entity
  end
end

2. Form Object

class UserRegistrationForm < StructuredParams::Params
  attribute :name, :string
  attribute :email, :string
  attribute :terms_accepted, :boolean
  
  validates :name, :email, presence: true
  validates :terms_accepted, acceptance: true
end

# Use in controller
def create
  form = UserRegistrationForm.new(UserRegistrationForm.permit(params))
  
  if form.valid?
    User.create!(form.attributes)
    redirect_to root_path
  else
    render :new
  end
end

Documentation

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/Syati/structured_params.

License

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

About

A Ruby library for structured parameter validation with type safety, providing clean error handling for complex nested parameters

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

 
 
 

Contributors