StronglyTyped

Build Status Dependency Status Code Climate

Description

This gem provides similar functionality as ruby core Struct but instead of inheritance i used mixins and even wrote something about my reasons to do so.

Same as Struct, it is a convenient way to bundle a number of attributes together using accessor methods with added features like basic type validation and type conversions when possible.

Similar Tools

From ruby core you have Struct and from stdlib OpenStruct.

Check virtus if you are looking for a full featured attributes settings for your Ruby Objects that requires complex automatic coercions among other things.

If you are looking for a nestable, coercible, Hash-like data structure take a look at structure gem.

Reasons

I took some ideas from others gems like virtus and structure but since none of them provided exactly what i needed then decided to create this gem for my sample gem project [dolarblue][] and the blog post i wrote about it.

Installation

Add gem 'strongly_typed' to your Gemfile then run bundle install or simply $ gem install strongly_typed

Usage

Include StronglyTyped::Model on you ruby objects then call attribute() to define them.

require 'strongly_typed'

class Person
  include StronglyTyped::Model

  attribute :id, Integer
  attribute :slug, String
end

Instance initialization with a hash, a.k.a named parameters

leo = Person.new(id: 1, slug: 'elgalu')
#=> #<Person:0x00c98 @id=1, @slug="elgalu">
leo.id   #=> 1
leo.slug #=> "elgalu"

Can also trust in the parameters order

leo = Person.new(1, 'elgalu')
#=> #<Person:0x00c99 @id=1, @slug="elgalu">
leo.id   #=> 1
leo.slug #=> "elgalu"

Hash Order doesn't matter

ana = Person.new(slug: 'anapau', id: 2)
#=> #<Person:0x00d33 @id=2, @slug="anapau">
ana.id   #=> 2
ana.slug #=> "anapau"

TypeError is raised when improper type

ted = Person.new(id: nil, slug: 'teddy')
#=> TypeError: can't convert nil into Integer

Check the full API here

Contributing

  1. Fork it.
  2. Make your feature addition or bug fix and create your feature branch.
  3. Update the Change Log.
  4. Add specs/tests for it. This is important so I don't break it in a future version unintentionally.
  5. Commit, create a new Pull Request.
  6. Check that your pull request passes the build.

TODO for StronglyTyped::Model

  • Add :default => 'value' to attribute() to support defaults
  • Add :required => true/false to attribute() so an ArgumentError is raised when not provided

TODO for StronglyTyped::Coercible

  • Extract coercer to another gem or use already existing coercion gem
  • Improve generic TypeError to also show attribute name, expected type and value received instead
  • On coercible.rb require gem 'double' to avoid requiring 'date' when user doesn't need that
  • Add support for BigDecimal

License

Released under the MIT License. See the LICENSE file for further details.

RubyGems | Documentation | Source | Bugtracker | Build Status | Dependency Status | Code Climate