TSpec

Build Status

TSpec adds a method of simple type check to Ruby.

:construction: Recommended for use only in hobby programming. Do not use this in production apps. :construction:

Installation

Add this line to your application's Gemfile:

gem 'tspec'

And then execute:

$ bundle

Or install it by yourself:

$ gem install tspec

Usage

TSpec can use #receive and #return method.

receive

receive defines the type of method arguments.

require 'tspec'

def echo(str)
  puts str
end.receive(str: String)

You can specify multiple type, too.

require 'tspec'

def echo(val)
  puts val
end.receive(val: [String, Float])

echo('hello')
echo(3.14)

If single method argument is given, you can skip keyword.

require 'tspec'

def join_array(arr)
  arr.join(' ')
end.receive([String])

puts join_array(%w(hello world))

You can specify Array content type, although it may seem strange.

require 'tspec'

def receive_string_array(arr)
  arr.join
end.receive(arr: [[String]])

puts receive_string_array(['hello', 'world'])

return

return defines the type of method return value.

require 'tspec'

def message
  'hello world'
end.return(String)

You can specify multiple return value, too.

require 'tspec'

def random_val
  [1.0, '1', :hello].sample
end.return(Float, String, Symbol)

10.times do
  v = random_val
end

Also, you can specify Array content type.

require 'tspec'

def message_list
  %w(hello ruby world)
end.return([String])

p message_list

Example

Combination of receive and return method.

require 'tspec'

def string2symbol(str)
  str.to_sym
end.receive(str: String).return(Symbol)

p string2symbol('hello') #=> :hello
p string2symbol(123)     #=> TSpec::ArgumentTypeError

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/siman-man/tspec. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available under the terms of the MIT License.