• Stars
    star
    24
  • Rank 986,245 (Top 20 %)
  • Language
    Crystal
  • License
    MIT License
  • Created almost 6 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

RethinkDB ORM for Crystal lang

RethinkDB ORM for Crystal Lang

CI Documentation

Extending ActiveModel for attribute definitions, callbacks and validations

Configuration

# Below is the list of settings exposed by RethinkORM and their defaults
RethinkORM::Settings.configure do |settings|
  settings.host = ENV["RETHINKDB_HOST"]? || "localhost"
  settings.port = (ENV["RETHINKDB_PORT"]? || 28015).to_i
  settings.db = ENV["RETHINKDB_DB"]? || ENV["RETHINKDB_DATABASE"]? || "test"
  settings.user = ENV["RETHINKDB_USER"]? || "admin"
  settings.password = ENV["RETHINKDB_PASSWORD"]? || ""
  settings.lock_expire = (ENV["RETHINKDB_LOCK_EXPIRE"]? || 30).to_i.seconds
  settings.lock_timeout = (ENV["RETHINKDB_LOCK_TIMEOUT"]? || 5).to_i.seconds
  settings.retry_interval = (ENV["RETHINKDB_TIMEOUT"]? || 2).to_i.seconds

  # Driver level reconnection attempts
  settings.retry_attempts = ENV["RETHINKDB_RETRIES"]?.try(&.to_i) || 10

  # ORM level query retries
  settings.query_retries = ENV["RETHINKDB_QUERY_RETRIES"]?.try &.to_i || 10
end

Callbacks

Register callbacks for save, update, create and destroy by setting the corresponding before/after callback handler.

class ModelWithCallbacks < RethinkORM::Base
  attribute address : String
  attribute age : Int32 = 10

  before_create :set_address
  after_update :set_age
  before_destroy do
    self.name = "joe"
  end

  def set_address
    self.address = "23"
  end

  def set_age
    self.age = 30
  end
end

Associations

Set associations with belongs_to, has_many and has_one.

Access children in parent by accessing the method correpsonding to the pluralised child. Children collection method name is generated by dumb pluralisation (appending an s). Optionally set children collection name in has_many by setting collection_name param.

The has_many association requires the belongs_to association on the child. By default, belongs_to creates a secondary index on the foreign key.

class Parent < RethinkORM::Base
  attribute name : String
  has_many Child, collection_name: "children"
end

class Child < RethinkORM::Base
  attribute age : Int32
  belongs_to Parent
  has_many Pet
end

class Pet < RethinkORM::Base
  attribute name : String
  belongs_to Child
end

parent = Parent.new(name: "Phil")
parent.children.empty? # => true

child = Child.new(age: 99)
child.pets.empty? # => true

belongs_to

Parameter Default
parent_class The parent class who this class is dependent on
dependent Sets destroy behaviour. One of :none, :destroy, :delete :none
create_index Create a secondary index on the foreign key true

has_many

Parameter Default
child_class The parent class who this class is dependent on
dependent Sets destroy behaviour. One of :none, :destroy, :delete :none
collection_name Define collection name, otherwise collection named through dumb pluralisation nil

has_one

Parameter Default
child_class The parent class who this class is dependent on
dependent Sets destroy behaviour. One of :none, :destroy, :delete :none
collection_name Define collection name, otherwise collection named through dumb pluralisation nil

Dependency

dependent param in the association definition macros defines the fate of the association on model destruction.
Default is :none, :destroy and :delete ensure destruction of association dependents.

Indexes

Set secondary indexes with secondary_index

Parameter
attribute defines the field on which to create an index

Changefeeds

Access the changefeed of a document or table through the changes query.
Defaults to watch for events on a table if no id provided.

Parameter Default
id id of document to watch for changes nil

Returns an iterator that emits NamedTuple(value: T, event: Event)

  • Changefeed::Event::Deleted events yield the deleted model
  • Changefeed::Event::Created events yield the created model
  • Changefeed::Event::Updated events yield the updated model
class Game < RethinkORM::Base
  attribute type : String
  attribute score : Int32, default: 0
end

ballgame = Game.create!(type: "footy")

# Observe changes on a single document
spawn do
  Game.changes(ballgame.id).each do |change|
    game = change.value
    puts "looks like the score is #{game.score}" unless game.nil?
  end
end

# Observe changes on a table
spawn do
  Game.changes.each do |change|
    game = change.value
    puts "#{game.type}: #{game.score}" unless game.nil?
    puts "game event: #{change.event}"
  end
end

Validations

Builds on active-model's validation

ensure_unique

Fails to validate if field with duplicate value present in db. If scope is set, the callback/block signature must be a tuple with types matching that of the scope. The field(s) are set with the result of the transform block upon successful validation

Parameter Default
field Model attribute on which to guarantee uniqueness
scope Attributes passed to the transform, defaults to :field nil
create_index Whether or not to generate a secondary index true
callback : T -> T Optional function to transform field value nil
block : T -> T Optional block to transform field value before querying nil

Timestamps

Adds creates created_at and updated_at attributes.

  • updated_at is set through the before_update callback, and initially set in the before_save callback.
  • created_at is set through the before_create callback.

The generated timestamp is UTC.

class Timo < RethinkORM::Base
  # Simply include the module
  include RethinkORM::Timestamps

  attribute name : String
end

More Repositories

1

spider-gazelle

A Rails esque web framework with a focus on speed and extensibility for crystal lang
Crystal
179
star
2

tasker

Scheduled tasks for crystal lang
Crystal
56
star
3

bindata

BinData - Parsing Binary Data in Crystal Lang
Crystal
48
star
4

ssh2.cr

libssh2 binding for Crystal language
Crystal
44
star
5

promise

Type aware promises for crystal lang
Crystal
42
star
6

action-controller

A rails-esque controller framework for crystal lang
Crystal
41
star
7

active-model

A rails-esque model framework for crystal lang
Crystal
28
star
8

crystal-mqtt

Crystal lang implementation of the MQTT protocol, a lightweight protocol for publish/subscribe messaging
Crystal
20
star
9

ffmpeg

ffmpeg crystal bindings
Crystal
19
star
10

crystal-ldap

a Crystal lang LDAP client
Crystal
18
star
11

qr-code

a QR Code implementation written in crystal lang
Crystal
17
star
12

crystal-snmp

SNMP implementation for crystal lang
Crystal
16
star
13

json-schema

Describe crystal-lang JSON serializable types with JSON Schema
Crystal
13
star
14

priority-queue

Priority Queue and Heap implementation for Crystal Lang
Crystal
13
star
15

bisect

Library for maintaining sorted Arrays
Crystal
12
star
16

pars

Parser combinator library for crystal-lang
Crystal
11
star
17

pinger

Microlibrary to perform ping requests with Crystal Lang
Crystal
11
star
18

telnet.cr

Telnet protocol helper for crystal lang
Crystal
11
star
19

crystal-openai

OpenAI ChatGPT, GPT-3, GPT-4, DALLยทE, Whisper API Client for Crystal
Crystal
11
star
20

pg-orm

Postgres ORM for Crystal Lang
Crystal
10
star
21

inactive-support

Utilities for crystal-lang
Crystal
10
star
22

mdns

Crystal Lang mDNS and DNS-SD Support
Crystal
8
star
23

tensorflow_lite

tensorflow lite bindings for crystal lang
Crystal
8
star
24

ed25519

Ed25519 high-performance public-key signature system for crystal lang
Crystal
7
star
25

secure-remote-password

Crystal implementation of the Secure Remote Password protocol (SRP-6a)
Crystal
7
star
26

crystal-gpt

ChatGPT plugin template that allows you to focus on writing actions, automatically generating the required metadata
Crystal
7
star
27

connect-proxy

crystal lang connect / HTTP proxy implementation
Crystal
7
star
28

simple_retry

a tool for retrying code blocks
Crystal
6
star
29

crunits

Physical quantity and units of measure conversion and math for crystal lang
Crystal
6
star
30

secrets-env

Extension to the crystal lang ENV module to support reading secrets
Crystal
6
star
31

v4l2.cr

crystal lang video for linux device helpers / bindings
Crystal
5
star
32

log_helper

Extension for Crystal Log to aid logging key-value data
Crystal
5
star
33

cmac

Crystal implementation of the Cipher-based Message Authentication Code (CMAC)
Crystal
5
star
34

readers-writer

A simple readers writer lock for crystal lang
Crystal
5
star
35

worker_pool

a basic fiber pool implementation for crystal lang
Crystal
5
star
36

matter

A complete Crystal implementation of the Matter protocol specification (https://buildwithmatter.com). Includes full support for controller, device, commissioning, secure communications, device types, and cluster definitions.
Crystal
5
star
37

guide

Spider Gazelle Documentation
Python
4
star
38

ntlm

NTLM authentication for crystal lang
Crystal
4
star
39

digest-auth

HTTP digest auth for crystal lang
Crystal
4
star
40

eventbus

Listen for Postgres database change events and publish them to event listeners
Crystal
3
star
41

knx

KNX protocol support for crystal lang
Crystal
3
star
42

tokenizer

Simplified binary stream tokenization for crystal lang
Crystal
2
star
43

crystal-dtls

DTLS support for crystal lang
Crystal
2
star
44

stumpy_resize

resizes stumpy canvas images in pure crystal
Crystal
2
star
45

upload-signer

Provide API for generating pre-signed URLs for file uploads to cloud storage
Crystal
2
star
46

SPAKE2_plus

a crystal lang implementation of SPAKE2+, a Password Authenticated Key Exchange (PAKE) protocol
Crystal
2
star
47

stomp

crystal lang implementation of the STOMP protocol
Crystal
1
star
48

tlv

Matter TLV encoder/decoder
Crystal
1
star
49

gpio.cr

crystal lang bindings for linux gpiod
Crystal
1
star
50

HKDF

HMAC-based Extract-and-Expand Key Derivation Function (HKDF) for crystal lang
Crystal
1
star
51

panopticon

Distributed tracing for services built in crystal-lang
Crystal
1
star
52

tflite_image

image classification and feature detection with tflite and crystal lang
Crystal
1
star
53

tflite_pipeline

video processing AI pipeline leveraging tflite_image
Crystal
1
star
54

link-header

Crystal Lang HTTP Link Header Parser
Crystal
1
star