Ree is a ruby framework to create modular Ruby applications. Ree introduces list of a following tools and concepts:
- Commands
- Project
- Packages
- Objects
- Contracts
- Schemas (Packages, Package, Object)
- Core Ruby Library Extensions
Before you start working with Ree framework please read documentation below to get usage examples and full understanding of the concepts provided.
Add this line to your application's Gemfile:
gem 'ree'And then execute:
$ bundle installOr install a gem into the local repository:
$ gem install reeAfter Ree installation one would get $ ree binary available in your shell.
$ ree help provides list of all available commands
$ ree help COMMAND_NAME shows command description with usage examples
$ ree init [options] generates project scaffold inside current directory
$ ree exec PACKAGE_NAME PATH_TO_EXEC [options] executes binary file from specific package folder
$ ree spec PACKAGE_NAME SPEC_MATCHER [options] runs rspec tests for specific package
$ ree gen.package PACKAGE_NAME [options] generates a package scaffold in a specified folder
$ ree gen.packages_json [options] generates Packages.schema.json
$ ree gen.package_json PACKAGE_NAME [options] generates Package.schema.json for specific package
$ ree gen.template TEMPLATE_NAME [options] generates template from PROJECT_DIR/.ree/templates/TEMPLATE_NAME folder with specified variables
First of all cd into your project root folder.
Run ree init command to generate Ree project scaffold. One would get output like this:
Generated: .rspec
Generated: .ruby-version
Generated: Gemfile
Generated: Packages.schema.json
Generated: bin/console
Generated: readme.md
Generated: ree.setup.rb
Generated: spec.init.rb.rspec file should be used to define global Rspec options.
.ruby-version By default this file would be populated with ruby version used to run ree init command.
Gemfile Global project Gemfile. Read about global Gemfile concept below.
Packages.schema.json Autogenerated schema of all project packages. Read information about Ree schemas below.
bin/console Global project console
readme.md Documentation for your project
ree.setup.rb This is a project setup file. It's being loaded when project starts.
spec.init.rb Global Rspec configuration file. One should use this file to load something before rspec suite starts.
Ree uses Global Gemfile Concept - one Gemfile for entire project. Ree-gems has there own gem dependencies (see gem packaging section). As a best practice we recommend to add require: false option to all none-ree gems in your Gemfile.
opts = {require: false}
gem 'ree'
gem 'oj', opts
gem 'roda', optsGems should be required in the package entry files (read about packages below).
# package entry path: ./packages/ree_json/package/ree_json.rb
require 'oj'
module ReeJson
include Ree::PackageDSL
package
endThis practice gives you the following benefits:
- single place to manage all your project gems
- easy way to understand which packages introduced gems to the project
- faster boot time for Rspec suite & App
Coming soon...
Coming soon...
Ree contracts bring code contracts to the Ruby language. Code contracts allow you to make some assertions about your code, and then check them to make sure they hold. This lets you:
- speed up your development and catch bugs earlier
- get full picture of method (arguments and there restrictions, method return value, thrown exceptions)
- make sure that the user gets proper messaging when a bug occurs.
A simple example:
contract Integer, Integer => Integer
def add(a, b)
a + b
endHere, the contract is contract Integer, Integer => Integer. This says that the add function takes two integers and returns an integer.
Copy this code into a file and run it:
require 'ree'
class Calc
contract Integer, Integer => Integer
def self.add(a, b)
a + b
end
end
Calc.add(1, "foo")You'll see a detailed error message like so:
Contract violation for Calc.add
- b: expected Integer, got String => "foo"
That tells you that your contract was violated! Method Call.add expected an Integer, and got a String ("foo") instead.
Ree contracts comes with a lot of built-in contracts, including the following:
- Basic types:
- Bool – checks that the argument is true or false
- Any – Passes for any argument. Use when the argument has no constraints.
- None – Fails for any argument. Use when the method takes no arguments.
- Logical combinations:
- Nilor – specifies that a value may be nil, e.g.
Nilor[String](equivalent toOr[String, nil]) - Or – passes if any of the given contracts pass, e.g.
Or[Fixnum, Float]
- Nilor – specifies that a value may be nil, e.g.
- Collections
- ArrayOf – checks that the argument is an array, and all elements pass the given contract, e.g.
ArrayOf[Integer] - SetOf – checks that the argument is a set, and all elements pass the given contract, e.g.
SetOf[Integer] - HashOf – checks that the argument is a hash, and all keys and values pass the given contract, e.g.
HashOf[Symbol, String] - RangeOf – checks that the argument is a range whose elements (#first and #last) pass the given contract, e.g.
RangeOf[Date]
- ArrayOf – checks that the argument is an array, and all elements pass the given contract, e.g.
- Array contracts
[String, Symbol]defines a contract for argument acceptingArrayof 2 items having symbol and string =>['hello', :world]
- Hash contracts
{a: Integer, b?: String}defines a contract for argument acceptingHashwith requiredakey havingIntegervalue and optionalbkey havingStringvalue if present =>{a: 1, b: 'string'}or{a: 1}
- Range contracts
(1..20)defines a contract for argument accepting argument value in the specified range.
- Splat contracts
- SplatOf - checks that all elements of splat argument pass the given contract
SplatOf[String] - Splat - allows to combine other contracts with
SplatOfcontract, e.g.Splat[SplatOf[String], Symbol]orSplat[Symbol, SplatOf[String]]orSplat[Integer, SplatOf[String], Symbol]
- SplatOf - checks that all elements of splat argument pass the given contract
- Contracts for keyword arguments
- Kwargs – checks that the argument is an options hash, and all required keyword arguments are present, and all values pass their respective contracts, e.g.
Kwargs[number: Integer, description: Optional[String]]
- Kwargs – checks that the argument is an options hash, and all required keyword arguments are present, and all values pass their respective contracts, e.g.
- Contracts for keyword splat arguments
- Ksplat – checks that the argument is an options hash, and all required or optional keyword splat arguments are present, and all values pass their respective contracts, e.g.
Ksplat[number: Integer, description?: Optional[String]]. Here number is a required keyword splat argument, description is an optional keyword splat argument.
- Ksplat – checks that the argument is an options hash, and all required or optional keyword splat arguments are present, and all values pass their respective contracts, e.g.
- Duck typing
- RespondTo – checks that the argument responds to all of the given methods, e.g.
RespondTo[:password, :credit_card]
- RespondTo – checks that the argument responds to all of the given methods, e.g.
- Miscellaneous
- Block – checks that method has required block argument.
- Optblock – checks that method has optional block argument.
- Exactly – checks that the argument has the given type, not accepting sub-classes, e.g.
Exactly[Integer]. - Eq – checks that the argument is precisely equal to the given value, e.g.
Eq[String]matches the class String and not a string instance. - SubclassOf – checks that the argument is a Class and is a subclass of specific class, e.g.
SubclassOf[Integer].
####Hello, World
contract String => nil
def hello(name)
puts "hello, #{name}!"
endYou always need to specify a contract for the return value. In this example, hello doesn't return anything, so the contract is nil. Now you know that you can use a constant like nil as the end of a contract. Valid values for a contract are:
- the name of a class (like String or Fixnum)
- a constant (like nil or 1)
- one of built-in contracts
- a Proc that takes a value and returns true or false to indicate whether the contract passed or not
- a class or an object that responds to the valid? (more on this later)
Some functions do not have arguments. Here is how to define contracts for them.
contract None => nil
def hello
puts 'hello'
endSometimes you want to force user to provide block argument:
contract Block => nil
def hello(&blk)
puts 'hello'
end
# success
hello { puts 'world' }
#failure
helloOptional block arguments should be defined like this:
contract Optblock => nil
def hello(&blk)
puts 'hello'
end
# both call will be successfull
hello { puts 'world' }
hello####A Double Function
contract Or[Fixnum, Float] => Or[Fixnum, Float]
def double(x)
2 * x
endSometimes you want to be able to choose between a few contracts. Or takes a variable number of contracts and checks the argument against all of them. If it passes for any of the contracts, then the Or contract passes. This introduces some new syntax. One of the valid values for a contract is an instance of a class that responds to the valid? method. This is what Or[Fixnum, Float] is. The longer way to write it would have been:
contract Or.new(Fixnum, Float) => Or.new(Fixnum, Float)All the built-in contracts have overridden the square brackets [] to give the same functionality. So you could write
contract Or[Fixnum, Float] => Or[Fixnum, Float]or
contract Or.new(Fixnum, Float) => Or.new(Fixnum, Float)whichever you prefer. They both mean the same thing here: make a new instance of Or with Fixnum and Float. Use that instance to validate the argument.
contract ArrayOf[Integer] => Integer
def product(vals)
total = 1
vals.each do |val|
total *= val
end
total
endThis contract uses the ArrayOf contract. Here's how ArrayOf works: it takes a contract. It expects the argument to be a list. Then it checks every value in that list to see if it satisfies that contract.
# passes
product([1, 2, 3, 4])
# fails
product([1, 2, 3, "foo"])contract SplatOf[Integer] => Integer
def product(*vals)
total = 1
vals.each do |val|
total *= val
end
total
end
product(1, 2, 3)This function uses splat args *vals instead of an array. To make a contract on splat args, use the SplatOf contract. It takes one contract as an argument and uses it to validate every element passed in through *vals. So for example,
SplatOf[Integer] means they should all be numbers.
SplatOf[Or[Integer, String]] means they should all be numbers or strings.
SplatOf[Any] means all arguments are allowed (Any is a contract that passes for any argument).
If an array is one of the arguments and you know how many elements it's going to have, you can put a contract on it:
# a function that takes an array of two elements...a person's age and a person's name.
contract [Integer, String] => nil
def person(data)
p data
endIf you don't know how many elements it's going to have, use ArrayOf.
contract ArrayOf[String] => nil
def person(data)
p data
endHere's a contract that requires a Hash. We can put contracts on each of the keys:
# note that you can define optional Hash arguments using ? mark in the end of key name.
contract {age: Integer, name: String, sirname?: String } => nil
def person(data)
p data
end
# succeeds
person(age: 21, name: 'John')
person(age: 21, name: 'John', sirname: 'Doe')
# fails
person(other: 21)Peruse this contract on the keys and values of a Hash.
contract HashOf[Symbol, Integer] => Integer
def give_largest_value(hsh)
hsh.values.max
endWhich you use like so:
# succeeds
give_largest_value(a: 1, b: 2, c: 3) # returns 3
# fails
give_largest_value("a" => 1, 2 => 2, c: 3)When you want a contract to match not just any string (i.e. contract String => nil), you can use regular expressions:
contract /World|Mars/i => nil
def greet(name)
puts "Hello #{name}!"
endLets say you are writing a simple function and require a bunch of keyword arguments:
contract String, Kwargs[port: Integer, user: String, password: String] => Connection
def connect(host, port: 5000, user:, password:)
# ...
end
# No value is passed for port
connect("example.org", user: "me", password: "none")In case function does not have any optional keyword args one can avoid usage of Kwargs at all:
contract String, Integer, String, String => Connection
def connect(host, port:, user:, password:)
# ...
end
# No value is passed for port
connect("example.org", user: "me", password: "none")In most of the cases keyword splat arguments should be used to define optional keyword arguments:
contract String, Ksplat[sirname?: String] => nil
def hello(name, **opts)
str = name
if opts[:String]
str += " #{opts[:sirname]}"
end
puts str
endTreat the return value as an array. For example, here's a function that returns two numbers:
contract Integer => [Integer, Integer]
def mult(x)
return x, x+1
endContracts are very easy to define. To re-iterate, there are 5 kinds of contracts:
- the name of a class (like String or Fixnum)
- a constant (like nil or 1)
- a Proc that takes a value and returns true or false to indicate whether the contract passed or not
- a class that responds to the valid? class method (more on this later)
- an instance of a class that responds to the valid? method (more on this later)
The first two don't need any extra work to define: you can just use any constant or class name in your contract and it should just work. Here are examples for the rest:
contract Proc.new { |x| x.is_a? Numeric } => Integer
def double(x)The Proc takes one parameter: the argument that is getting passed to the function. It checks to see if it's a Numeric. If it is, it returns true. Otherwise it returns false. It's not good practice to write a Proc right in your contract...if you find yourself doing it often, write it as a class instead.
class Num
def self.valid? val
val.is_a? Numeric
end
endThe valid? class method takes one parameter: the argument that is getting passed to the function. It returns true or false.
contract Num => Num
def double(x)
x
endclass Num
def valid? val
val.is_a? Numeric
end
end
contract Num.new => Num.new
def double(x)
x
endIf you want to disable contracts, set the NO_CONTRACTS environment variable. This will disable contracts and you won't have a performance hit.
Coming soon...
Coming soon...
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. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and the created tag, and push the .gem file to rubygems.org.
Bug reports and pull requests are welcome on GitHub at https://github.com/glabix/ree. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.
The gem is available as open source under the terms of the MIT License.
Everyone interacting in the Ree project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.