Project

typical

0.0
No commit activity in last 3 years
No release in over 3 years
A Ruby library to describe the types of your data and ways to validate them.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies
 Project Readme

Typical

This library provides a DSL to describe the types of your data and ways to validate them.

Installation

Add this line to your application's Gemfile:

gem "typical"

And then execute:

$ bundle

Or install it yourself as:

$ gem install typical

Usage

DSL

To specify type information, you can use the Typical::DSL module.

require "typical/dsl"
include Typical::DSL

The bang methods are used to define types.

String!                    # => #<Type:String>

You can allow multiple types by creating a union of them.

String! | Integer!         # => #<Type:Union [#<Type:String>, #<Type:Integer>]>

Sometimes a field can also be null.

String! | Integer! | null  # => #<Type:Union [#<Type:String>, , #<Type:Integer>, #<Type:NilClass>]>

If you’re defining a single type, but nullable, use the question mark methods instead.

String?                    # => #<Type:Union [#<Type:String>, #<Type:NilClass>]>

You can have collections too, you use them like you normally would.

Set!(String!, Integer!)    # => #<Type:Set [#<Type:Union [#<Type:String>, #<Type:Integer>]>]>
Array!(String!, Integer!)  # => #<Type:Array [#<Type:Union [#<Type:String>, #<Type:Integer>]>]>
Hash!(String! => Integer!) # => #<Type:Hash { [#<Type:Union [#<Type:String>]>] => [#<Type:Union [#<Type:Integer>]>] }>

Validation

NOTE: This is not yet implemented.

typing = Array!(String!)
typing.valid?("string")    # => false
typing.valid?([nil])       # => false
typing.valid?([])          # => true
typing.valid?(["string"])  # => true

Mongoid

NOTE: This is not yet implemented.

This Mongoid integration allows you to both reflect on the data types in your database and validate incoming data.

class Artist
  include Mongoid::Document
  include Typical::Mongoid

  field :name, type: String?
  field :image_versions, type: Array!(Symbol!)
  field :image_urls, type: Hash!(String! => String!)
end

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake test 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/alloy/typical.

License

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