# Introduction to Ree 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. ## Installation Add this line to your application's Gemfile: ```ruby gem 'ree' ``` And then execute: ```bash $ bundle install ``` Or install a gem into the local repository: ```bash $ gem install ree ``` ## Ree Commands After 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 ## Setup Ree Project First of all `cd` into your project root folder. Run `ree init` command to generate Ree project scaffold. One would get output like this: ```bash 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. ## Global Gemfile Concept 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`. ```ruby opts = {require: false} gem 'ree' gem 'oj', opts gem 'roda', opts ``` Gems should be required in the package entry files (read about packages below). ```ruby # package entry path: ./packages/ree_json/package/ree_json.rb require 'oj' module ReeJson include Ree::PackageDSL package end ``` This 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 ## Ree Packages Coming soon... ## Ree Objects Coming soon... ## Ree Contracts 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. ### Basics A simple example: ```ruby contract Integer, Integer => Integer def add(a, b) a + b end ``` Here, 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: ```ruby 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. ### Built-in Contracts 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 to `Or[String, nil]`) - **Or** – passes if any of the given contracts pass, e.g. `Or[Fixnum, Float]` - 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]` - Array contracts - `[String, Symbol]` defines a contract for argument accepting `Array` of 2 items having symbol and string => `['hello', :world]` - Hash contracts - `{a: Integer, b?: String}` defines a contract for argument accepting `Hash` with required `a` key having `Integer` value and optional `b` key having `String` value 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 `SplatOf` contract, e.g. `Splat[SplatOf[String], Symbol]` or `Splat[Symbol, SplatOf[String]]` or `Splat[Integer, SplatOf[String], Symbol]` - 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]]` - 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. - Duck typing - **RespondTo** – checks that the argument responds to all of the given methods, e.g. `RespondTo[:password, :credit_card]` - 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]`. ### More Examples ####Hello, World ```ruby contract String => nil def hello(name) puts "hello, #{name}!" end ``` You 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. ```ruby contract None => nil def hello puts 'hello' end ``` #### Function with required block Sometimes you want to force user to provide block argument: ```ruby contract Block => nil def hello(&blk) puts 'hello' end # success hello { puts 'world' } #failure hello ``` #### Function with optional block Optional block arguments should be defined like this: ```ruby contract Optblock => nil def hello(&blk) puts 'hello' end # both call will be successfull hello { puts 'world' } hello ``` ####A Double Function ```ruby contract Or[Fixnum, Float] => Or[Fixnum, Float] def double(x) 2 * x end ``` Sometimes 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: ```ruby 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 ```ruby contract Or[Fixnum, Float] => Or[Fixnum, Float] ``` or ```ruby 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. #### A Product Function ```ruby contract ArrayOf[Integer] => Integer def product(vals) total = 1 vals.each do |val| total *= val end total end ``` This 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. ```ruby # passes product([1, 2, 3, 4]) # fails product([1, 2, 3, "foo"]) ``` #### Another Product Function ```ruby 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). #### Contracts On Arrays 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: ```ruby # 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 end ``` If you don't know how many elements it's going to have, use `ArrayOf`. ```ruby contract ArrayOf[String] => nil def person(data) p data end ``` #### Contracts On Hashes Here's a contract that requires a Hash. We can put contracts on each of the keys: ```ruby # 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. ```ruby contract HashOf[Symbol, Integer] => Integer def give_largest_value(hsh) hsh.values.max end ``` Which you use like so: ```ruby # succeeds give_largest_value(a: 1, b: 2, c: 3) # returns 3 # fails give_largest_value("a" => 1, 2 => 2, c: 3) ``` #### Contracts On Strings When you want a contract to match not just any string (i.e. `contract String => nil`), you can use regular expressions: ```ruby contract /World|Mars/i => nil def greet(name) puts "Hello #{name}!" end ``` #### Contracts On Keyword Arguments Lets say you are writing a simple function and require a bunch of keyword arguments: ```ruby 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: ```ruby 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") ``` #### Contracts On Keyword Splat Arguments In most of the cases keyword splat arguments should be used to define optional keyword arguments: ```ruby contract String, Ksplat[sirname?: String] => nil def hello(name, **opts) str = name if opts[:String] str += " #{opts[:sirname]}" end puts str end ``` #### Returning Multiple Values Treat the return value as an array. For example, here's a function that returns two numbers: ```ruby contract Integer => [Integer, Integer] def mult(x) return x, x+1 end ``` ### Defining Your Own Contracts Contracts 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: #### A Proc ```ruby 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. #### A Class With valid? As a Class Method ```ruby class Num def self.valid? val val.is_a? Numeric end end ``` The `valid?` class method takes one parameter: the argument that is getting passed to the function. It returns true or false. ```ruby contract Num => Num def double(x) x end ``` #### A Class With valid? As an Instance Method ```ruby class Num def valid? val val.is_a? Numeric end end contract Num.new => Num.new def double(x) x end ``` ### Disabling contracts If you want to disable contracts, set the `NO_CONTRACTS` environment variable. This will disable contracts and you won't have a performance hit. ## Ree Schemas Coming soon... ## Ruby Std Lib Extensions Coming soon... ## 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`. 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](https://rubygems.org). ## Contributing 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](https://github.com/glabix/ree/ree/blob/main/CODE_OF_CONDUCT.md). ## License The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). ## Code of Conduct Everyone interacting in the Ree project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/glabix/ree/ree/blob/main/CODE_OF_CONDUCT.md).