Project

typed_attr

0.0
No commit activity in last 3 years
No release in over 3 years
Typed Attributes and Composite Types for Functional Programming in Ruby
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.3
~> 0.9
>= 0
~> 2.14
~> 0.8
 Project Readme

CompositeType

Composite Types for Ruby

Usage

Composite Types can be constructed to match deeper data structures:

h = { "a" => 1, "b" => :symbol }
Hash.of(String.with(Integer|Symbol)) === h  # => true

Defining types through Modules:

module Even
  def self.=== x
    Integer === x and x.even?
  end
end
Array.of(Even) === [ 2, 4, 10 ]

Composite types create dynamic Modules that redefine the #=== pattern matching operator. Thus composite types can be used in "case when" clauses:

case h
when Hash.of(String.with(Users))  ...
when Hash.of(Symbol.with(Object)) ...
end

Logical operators: #|, #&, #~ are supported:

a = [ 1, 2, 3 ]
Array.of(Positive & Integer) === a   # => true
Array.of(~ NilClass) === a           # => true

b = [ 1, -2, 3 ]
Array.of(Positive & Integer) === b   # => false

c = [ 1, 1.5, 3 ]
Array.of(Positive & Integer) === c   # => false

d = [ 1, nil, 3 ]
Array.of(~ NilClass) === d           # => false

Composite types are cached indefinitely, therefore anonymous Modules cannot be composed.

See spec/lib/composite_type_spec.rb for more examples.

Installation

Add this line to your application's Gemfile:

gem 'composite_type'

And then execute:

$ bundle

Or install it yourself as:

$ gem install composite_type

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request