Skip to content
Struct + validation + default_value + aliasable + inheritable + etc...
Ruby
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
benchmark
example
lib
test
.gitignore
.travis.yml
.yardopts
Gemfile
MIT-LICENSE
README.md
Rakefile
striuct.gemspec

README.md

striuct

Build Status Gem Version Dependency Status

Description

Struct++

Features

Strict

  • Easy and Flexible Validations
  • Prevent to conflict member names
  • Lock setters for each member

Useful

  • Hook just before setters
  • Default value
  • Member aliasing
  • Inheritable
  • Handling between nil <-> unassigned
  • More flendly API for Hash

Onepoint

  • Base API looks like Struct
  • Pure Ruby :)

Usage

Overview - Case 1

require 'striuct'

class Person < Striuct
  member :fullname, AND(String, /\A.+\z/)     # Flexible Validation
  alias_member :name, :fullname               # Use other name
end

class User < Person                           # Inheritable
  member :id, Integer,                        # Looks typed validation
              default_proc: ->{User.next_id}  # With default value

  @id = 0
  def self.next_id
    @id += 1
  end
end

john = User.new 'john'
john[:name]              #=> 'john' 
john.name = ''           #=> Exception        # Validate with setter
john.id                  #=> 1
ken = User[name: 'ken']                       # Construct from hash
ken.id                   #=> 2

Overview - Case 2

class Foo < Striuct
  member :foo
  member :bar, Numeric
  member :with_adjuster, Integer,
                         &->v{Integer v}      # Use adjuster before a setter
end

foo = Foo.new

# nil <-> unaasigned
foo.foo                  #=> nil
foo.assigned?(:foo)      #=> false
foo.foo = nil
foo.assigned?(:foo)      #=> true

# Lock to a member
foo.lock(:foo)
foo.foo = nil            #=> error

foo.bar = 1.2            #=> pass             # memorize 1.2's class is Float
foo.bar = 1              #=> error            # 1 is not Float

# With adjuster
foo.with_adjuster = '5'
foo.with_adjuster        #=> 5                # Casted via adjuster

Overview - Case 3

class UseMustOption < Striuct
  member :foo, Integer, must: true
end

UseMustOption.new #=> InvalidOperationError "`foo` require a value under `must` option "

How to build flexible conditions ?

Requirements

Install

gem install striuct

Link

License

The MIT X11 License
Copyright (c) 2011 Kenichi Kamiya
See MIT-LICENSE for further details.

You can’t perform that action at this time.