https://github.com/ravendb/ravendb-ruby-client
https://github.com/ravendb/ravendb-ruby-client
Last synced: 7 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/ravendb/ravendb-ruby-client
- Owner: ravendb
- License: mit
- Created: 2017-05-26T09:42:08.000Z (over 8 years ago)
- Default Branch: v4.0
- Last Pushed: 2018-08-08T06:48:41.000Z (about 7 years ago)
- Last Synced: 2025-04-09T16:15:28.233Z (7 months ago)
- Language: Ruby
- Size: 598 KB
- Stars: 4
- Watchers: 6
- Forks: 5
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# RavenDB client for Ruby
[](https://travis-ci.org/ravendb/ravendb-ruby-client)
## Installation
For global install run:
```bash
gem install --save ravendb
```
Or require `ravendb` gem in your project's `Gemfile`:
```
source 'https://rubygems.org'
gem 'ravendb'
```
## Getting started
1. Declare document models as classes. Attributes should be just an instance variables accessible via `attr_accessor()`
```ruby
class Product
:attr_accessor :id, :title, :price, :currency,
:storage, :manufacturer, :in_stock,
:last_update
def initialize(
id = nil,
title = '',
price = 0,
currency = 'USD',
storage = 0,
manufacturer = '',
in_stock = false,
last_update = nil
)
@id = id
@title = title
@price = price
@currency = currency
@storage
@manufacturer = manufacturer
@in_stock = in_stock
@last_update = last_update
end
end
```
2. Require `ravendb` gem and models classes in your application:
```ruby
require 'ravendb'
require 'models/product'
```
3. Configure document store:
```ruby
RavenDB.store.configure do |config|
config.urls = ["database url"]
config.database = 'database name'
end
```
3. Open a session:
```ruby
session = RavenDB.store.open_session
```
4. Do some actions with documents:
```ruby
product = session.load('Products/1-A')
product.in_stock = true
```
5. Call `save_changes` when you'll finish working with a session:
```ruby
session.save_changes
```
6. Also you can wrap all actions done with a session in a nested block:
```ruby
RavenDB.store.open_session do |session|
product = session.load('Products/1-A')
product.in_stock = true
session.save_changes
end
```
## CRUD example
### Creating documents
```ruby
product = Product.new('iPhone X', 999.99, 'USD', 64, 'Apple', true, DateTime.new(2017, 10, 1, 0, 0, 0))
RavenDB.store.open_session do |session|
product = session.store(product)
puts product.id # will output Products/- e.g. Products/1-A
session.save_changes
end
```
### Loading documents
```ruby
RavenDB.store.open_session do |session|
product = session.load('Products/1-A')
puts product.title # iPhone X
puts product.id # Products/1-A
end
```
### Updating documents
```ruby
RavenDB.store.open_session do |session|
product = session.load('Products/1-A')
product.in_stock = false
product.last_update = DateTime.now
session.save_changes
product = session.load('Products/1-A')
puts product.in_stock.inspect # false
puts product.last_update # outputs current date
end
```
### Deleting documents
```ruby
RavenDB.store.open_session do |session|
product = session.load('Products/1-A')
session.delete(product)
# or you can just do
# session.delete('Products/1-A')
session.save_changes
product = session.load('Products/1-A')
puts product.inspect # nil
end
```
## Querying documents
1. Create `RavenDB::DocumentQuery` instance using `query` method of session:
```ruby
query = session.query({
:collection => 'Products', # specify which collection you'd like to query
# optionally you may specify an index name for querying
# :index_name => 'PopularProductsWithViewsCount'
})
```
2. Apply conditions, ordering etc. Query supports chaining calls:
```ruby
query
.wait_for_non_stale_results
.using_default_operator(RavenDB::QueryOperator::AND)
.where_equals('manufacturer', 'Apple')
.where_equals('in_stock', true)
.where_between('last_update', DateTime.strptime('2017-10-01T00:00:00', '%Y-%m-%dT%H:%M:%S'), DateTime::now)
.order_by('price')
```
3. Finally, you may get query results:
```
documents = query.all
```
5. If you used `select_fields` method in in query, pass document class (or class name) as `:document_type` parameter in the query options:
```ruby
products_with_names_only = session.query({
:document_type => Product,
:collection => 'Products'
})
.select_fields(['name'])
.wait_for_non_stale_results
.all
```
#### RavenDB::DocumentQuery methods overview
Method
RQL / description
select_fields(fields, projections = nil)
select field1 [as projection1], ...
distinct
select distinct
where_equals(field_name, value,
exact = false)
where fieldName = <value>
where_not_equals(field_name, value,
exact = false)
where fieldName != <value>
where_in(field_name, values, exact = false)
where fieldName in (<value1>, <value2>, ...)
where_starts_with(field_name, value)
where startsWith(fieldName, '<value>')
where_ends_with(field_name, value)
where endsWith(fieldName, '<value>')
where_between(field_name, from, to,
exact = nil)
where fieldName BETWEEN <start> AND <end>
where_greater_than(field_name, value,
exact = nil)
where fieldName > <value>
where_greater_than_or_equal(field_name,
value, exact = nil)
where fieldName >= <value>
where_less_than(field_name, value,
exact = nil)
where fieldName < <value>
where_less_than_or_equal(field_name,
value, exact = nil)
where fieldName <= <value>
where_exists(field_name)
where exists(fieldName)
contains_any(field_name, values)
where fieldName in (<value1>, <value2>, ...)
contains_all(field_name, values)
where fieldName all in (<value1>, <value2>, ...)
search(field_name, search_terms,
operator = RavenDB::SearchOperator::OR)
Performs full-text search
open_subclause
Opens subclause (
close_subclause
Closes subclause )
negate_next
Adds not before next condition
and_also
Adds and before next condition
or_else
Adds or before next condition
using_default_operator(operator)
Sets default operator (which will be used if no and_also / or_else was called. Just after query instantiation, OR is used as default operator. Default operator can be changed only before adding any conditions
order_by(field, ordering_type = nil)
order by field
order_by_descending(field,
ordering_type = nil)
order by field desc
random_ordering(seed = nil)
order by random()
take(count)
Limits the number of result entries to count
skip(count)
Skips first count results
first
Returns first document from result set
single
Returns single document matching query criteria. If there are no such document or more then one - throws an Exception
all
Returns all documents from result set (considering take / skip options)
count
Returns count of all documents matching query criteria (non-considering take / skip options)
## Working with secured server
1. Instantiate `RavenDB::StoreAuthOptions`. Pass contents of the .pem certificate and passphrase (optional) to constructor:
```ruby
certificate = < ,
:target => ,
:original_attribute => ,
:serialized_attribute => ,
:original_value => ,
:serialized_value => ,
:metadata =>
}
```
2. Store target attribute name/value into the `serialized_attribute`/`serialized_value` properties of `serialized` parameter:
```ruby
# serializers/custom.rb
class CustomAttributeSerializer < RavenDB::AttributeSerializer
def on_serialized(serialized)
metadata = serialized[:metadata]
case metadata['Raven-Ruby-Type']
when TestCustomSerializer.name
serialized[:serialized_attribute] = serialized[:original_attribute].camelize(:lower)
if serialized[:original_attribute] == 'item_options'
serialized[:serialized_value] = serialized[:original_value].join(",")
end
else
nil
end
end
def on_unserialized(serialized)
metadata = serialized[:metadata]
case metadata['Raven-Ruby-Type']
when TestCustomSerializer.name
serialized[:serialized_attribute] = serialized[:original_attribute].underscore
if serialized[:original_attribute] == 'itemOptions'
serialized[:serialized_value] = serialized[:original_value].split(",").map { |option| option.to_i }
end
else
nil
end
end
end
```
3. Pass your serializer object to `conventions.add_attribute_serializer`:
```ruby
require 'ravendb'
require './serializers/custom'
store.conventions.add_attribute_serializer(serializer)
sesssion = store.open_session
session.store(Item.new(nil, 'First Item', [1, 2, 3]))
session.save_changes
session = store.open_session
item = session.load('Items/1-A')
puts item.item_id # Items/1-A
puts item.item_title # First Item
puts item.item_options.inspect # [1, 2, 3]
response = store.get_request_executor.execute(RavenDB::GetDocumentCommand.new('Items/1-A'))
raw_document = response['Results'].first
puts raw_document['@metadata']['@id'] # Items/1-A
puts raw_document['itemTitle'] # First Item
puts raw_document['itemOptions'] # "1,2,3"
```
## Running tests
```bash
URL= [CERTIFICATE= [PASSPHRASE=<.pem certificate passphrase>]] rake test
```