Project

argspec

0.0
Repository is archived
No commit activity in last 3 years
No release in over 3 years
RSpec style(ish) checks for arguments
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.11
~> 10.0
~> 3.0
 Project Readme

Argument Specification

Using argspec, you can easily validate that arguments match your required specification.

Installation

Add this line to your application's Gemfile:

gem 'argspec'

And then execute:

$ bundle

Or install it yourself as:

$ gem install argspec

Usage

Let's say you have the following Person class:

class Person
  attr_reader :name, :gender, :birthdate

  def initialize(name, gender, birthdate)
    @name = name
    @gender = gender
    @birthdate = birthdate
  end
end

You'd like to validate those three arguments match the expected type. You might come up with something like this:

class Person
  attr_reader :name, :gender, :birthdate

  def initialize(name, gender, birthdate)
    raise ArgumentError, 'The name must be a string and must not be nil.' if !name.is_a?(String) || name.empty?
    raise ArgumentError, 'The gender must be a symbol.' unless gender.is_a?(Symbol)
    raise ArgumentError, 'The birthdate must be a date.' unless birthdate.is_a?(Date)

    @name = name
    @gender = gender
    @birthdate = birthdate
  end
end

That will work fine, but it looks a little messy. Let's use argspec instead:

class Person
  include ArgumentSpecification::DSL

  attr_reader :name, :gender, :birthdate

  def initialize(name, gender, birthdate)
    argument(name) do
      should be_a(String)
      should_not be_empty
    end

    argument(gender) { should be_a(Symbol) }
    argument(birthdate) { should be_a(Date) }

    @name = name
    @gender = gender
    @birthdate = birthdate
  end
end

That's better. It's now really clear what validations you're performing.

Method chaining is also supported:

class Person
  include ArgumentSpecification::DSL

  attr_reader :name, :gender, :birthdate

  def initialize(name, gender, birthdate)
    argument(name) { should(be_a(Symbol)).and_not(be_empty) }
    argument(gender) { should be_a(Symbol) }
    argument(birthdate) { should be_a(Date) }

    @name = name
    @gender = gender
    @birthdate = birthdate
  end
end

Development

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