couchbase-orm 2.0.4 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/deploy.yml +45 -0
  3. data/.github/workflows/test.yml +18 -13
  4. data/README.md +12 -0
  5. data/couchbase-orm.gemspec +2 -2
  6. data/docusaurus/.gitignore +20 -0
  7. data/docusaurus/README.md +41 -0
  8. data/docusaurus/babel.config.js +3 -0
  9. data/docusaurus/docs/tutorial-ruby-couchbase-orm/01-introduction.md +49 -0
  10. data/docusaurus/docs/tutorial-ruby-couchbase-orm/02-installation.md +108 -0
  11. data/docusaurus/docs/tutorial-ruby-couchbase-orm/03-defining-models.md +239 -0
  12. data/docusaurus/docs/tutorial-ruby-couchbase-orm/04-querying.md +154 -0
  13. data/docusaurus/docs/tutorial-ruby-couchbase-orm/05-persistence.md +93 -0
  14. data/docusaurus/docs/tutorial-ruby-couchbase-orm/06-associations-and-validations.md +236 -0
  15. data/docusaurus/docs/tutorial-ruby-couchbase-orm/07-sqlpp-queries.md +180 -0
  16. data/docusaurus/docs/tutorial-ruby-couchbase-orm/08-views.md +158 -0
  17. data/docusaurus/docs/tutorial-ruby-couchbase-orm/09-nested-documents.md +138 -0
  18. data/docusaurus/docs/tutorial-ruby-couchbase-orm/10-enums.md +91 -0
  19. data/docusaurus/docs/tutorial-ruby-couchbase-orm/11-encryption.md +114 -0
  20. data/docusaurus/docs/tutorial-ruby-couchbase-orm/12-logging.md +48 -0
  21. data/docusaurus/docs/tutorial-ruby-couchbase-orm/13-troubleshooting.md +41 -0
  22. data/docusaurus/docs/tutorial-ruby-couchbase-orm/_category_.json +8 -0
  23. data/docusaurus/docusaurus.config.ts +122 -0
  24. data/docusaurus/package-lock.json +14540 -0
  25. data/docusaurus/package.json +47 -0
  26. data/docusaurus/sidebars.ts +31 -0
  27. data/docusaurus/src/components/HomepageFeatures/index.tsx +69 -0
  28. data/docusaurus/src/components/HomepageFeatures/styles.module.css +11 -0
  29. data/docusaurus/src/css/custom.css +30 -0
  30. data/docusaurus/src/pages/index.module.css +23 -0
  31. data/docusaurus/src/pages/index.tsx +43 -0
  32. data/docusaurus/src/pages/markdown-page.md +7 -0
  33. data/docusaurus/static/.nojekyll +0 -0
  34. data/docusaurus/static/CNAME +1 -0
  35. data/docusaurus/static/img/familiar.svg +1 -0
  36. data/docusaurus/static/img/fast.svg +1 -0
  37. data/docusaurus/static/img/logo.svg +1 -0
  38. data/docusaurus/static/img/undraw_docusaurus_mountain.svg +171 -0
  39. data/docusaurus/static/img/undraw_docusaurus_react.svg +170 -0
  40. data/docusaurus/static/img/undraw_docusaurus_tree.svg +40 -0
  41. data/docusaurus/tsconfig.json +7 -0
  42. data/lib/couchbase-orm/types/date_time.rb +2 -1
  43. data/lib/couchbase-orm/utilities/query_helper.rb +1 -1
  44. data/lib/couchbase-orm/version.rb +1 -1
  45. metadata +43 -10
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7f70a9e7ebdde5781a23268a9d400a917fcea2d9432a61f0b374280c2d534325
4
- data.tar.gz: a3cb52d01386be648eecce010f96399325771b0b50c32f92dec3f91b41fdb628
3
+ metadata.gz: f52bb1912f8b6e060c4daffc1b9ef0bd0922b7dc4035c774743839ea54abcab4
4
+ data.tar.gz: ba9cf86a6014a14a671c9a209f2c8ba58bd2acd8b1d54720af8c9237c4812cbc
5
5
  SHA512:
6
- metadata.gz: 7bb46f6fe815f3378e39421453b3a0b901fe81cd35f49ec10505a9d6e12d11d201d58ce02a436adb8b569adc2e01aec7b5c07bdd264bc50a68ff1074d0f574f8
7
- data.tar.gz: 5f542c3227c7587c1ad14c43f64d35e2a072bc4d39165fd9c6983bf86f3061c220360ce86393cbc67e61c537833bfb6679ed5ad3b3edebc7c2a00065e02997b3
6
+ metadata.gz: 1c3dc0311028fb1edf5612632f9b8bbadd89bd540416f08989331075ee052d915f58481b2879b15f946810c0e4c735b8130d994c0f796c9cae4d50bf0a0e50ea
7
+ data.tar.gz: '013937e07a05ec6386be0c65ef72dba41c67aa902680d5cb5f0bd936eaf592a1d5b024d7d4c6bcd06d5bc7195bb4bb44f8afc99beb010288f1be9807e117e207'
@@ -0,0 +1,45 @@
1
+ name: Deploy to GitHub Pages
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - master
7
+
8
+ permissions:
9
+ contents: write
10
+
11
+ jobs:
12
+ deploy:
13
+ name: Deploy to GitHub Pages
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ with:
18
+ fetch-depth: 0
19
+ - uses: actions/setup-node@v4
20
+ with:
21
+ node-version: 20
22
+
23
+ - name: Install dependencies
24
+ run: |
25
+ cd docusaurus
26
+ yarn install
27
+
28
+ - name: Build website
29
+ run: |
30
+ cd docusaurus
31
+ yarn build
32
+
33
+ - name: Deploy to GitHub Pages
34
+ uses: peaceiris/actions-gh-pages@v3
35
+ with:
36
+ github_token: ${{ secrets.GITHUB_TOKEN }}
37
+ # Build output to publish to the `gh-pages` branch:
38
+ publish_dir: ./docusaurus/build
39
+ # The following lines assign commit authorship to the official
40
+ # GH-Actions bot for deploys to `gh-pages` branch:
41
+ # https://github.com/actions/checkout/issues/13#issuecomment-724415212
42
+ # The GH actions bot is used by default if you didn't specify the two fields.
43
+ # You can swap them out with your own user credentials.
44
+ user_name: github-actions[bot]
45
+ user_email: 41898282+github-actions[bot]@users.noreply.github.com
@@ -11,27 +11,32 @@ jobs:
11
11
  strategy:
12
12
  matrix:
13
13
  include:
14
+ - ruby: '3.4'
15
+ active-model: '8.0.2'
16
+ couchbase: '7.2.3'
17
+ - ruby: '3.3'
18
+ active-model: '8.0.0'
19
+ couchbase: '7.2.3'
14
20
  - ruby: '3.3'
15
- gemfile: '7.1.0'
21
+ active-model: '7.2'
16
22
  couchbase: '7.2.3'
17
23
  - ruby: '3.2'
18
- gemfile: '7.1.0'
24
+ active-model: '7.2.0'
19
25
  couchbase: '7.1.1'
20
- - ruby: '3.0'
21
- gemfile: '7.0.0'
26
+ - ruby: '3.2'
27
+ active-model: '7.1.0'
22
28
  couchbase: '6.6.5'
23
- - ruby: '3.0'
24
- gemfile: '7.0.0'
25
- couchbase: '7.1.0'
26
- - ruby: '2.7'
27
- gemfile: '7.0.0'
29
+ - ruby: '3.1'
30
+ active-model: '7.1.0'
28
31
  couchbase: '7.1.0'
29
32
  fail-fast: false
30
- runs-on: ubuntu-20.04
31
- name: ${{ matrix.ruby }} rails-${{ matrix.gemfile }} couchbase-${{ matrix.couchbase }}
33
+ runs-on: ubuntu-24.04
34
+ name: ${{ matrix.ruby }} rails-${{ matrix.active-model }} couchbase-${{ matrix.couchbase }}
32
35
  steps:
33
36
  - uses: actions/checkout@v3
34
- - run: sudo apt-get update && sudo apt-get install libevent-dev libev-dev python-httplib2
37
+ - run: sudo apt-get update && sudo apt-get install libevent-dev libev-dev python3-httplib2
38
+ - run: wget http://security.ubuntu.com/ubuntu/pool/universe/n/ncurses/libtinfo5_6.3-2ubuntu0.1_amd64.deb
39
+ - run: sudo apt install ./libtinfo5_6.3-2ubuntu0.1_amd64.deb
35
40
  - uses: ruby/setup-ruby@v1
36
41
  with:
37
42
  ruby-version: ${{ matrix.ruby }}
@@ -39,7 +44,7 @@ jobs:
39
44
  - run: sudo ./ci/run_couchbase.sh $COUCHBASE_VERSION $COUCHBASE_BUCKET $COUCHBASE_USER $COUCHBASE_PASSWORD
40
45
  - run: bundle exec rspec
41
46
  env:
42
- ACTIVE_MODEL_VERSION: ${{ matrix.gemfile }}
47
+ ACTIVE_MODEL_VERSION: ${{ matrix.active-model }}
43
48
  BUNDLE_JOBS: 4
44
49
  BUNDLE_PATH: vendor/bundle
45
50
  COUCHBASE_BUCKET: default
data/README.md CHANGED
@@ -393,3 +393,15 @@ The request above pulls the same database document each time and returns it. A s
393
393
  |Response time|0.88 secs|0.34 secs|
394
394
  |Transaction rate|204.25 trans/sec|366.57 trans/sec|
395
395
  |Request Code|[ruby-model-app](https://github.com/QuayPay/coauth/blob/95bbf5e5c3b3340e5af2da494b90c91c5e3d6eaa/app/controllers/auth/authorities_controller.rb#L6)|[couch-orm-app](https://github.com/QuayPay/coauth/blob/87f6fdeaab784ba252a5d38bbcf9e6b0477bb504/app/controllers/auth/authorities_controller.rb#L8)|
396
+
397
+ ---
398
+
399
+ ## 📢 Support Policy
400
+
401
+ We truly appreciate your interest in this project!
402
+ This project is **community-maintained**, which means it's **not officially supported** by our support team.
403
+
404
+ If you need help, have found a bug, or want to contribute improvements, the best place to do that is right here — by [opening a GitHub issue](https://github.com/Couchbase-Ecosystem/couchbase-ruby-orm/issues).
405
+ Our support portal is unable to assist with requests related to this project, so we kindly ask that all inquiries stay within GitHub.
406
+
407
+ Your collaboration helps us all move forward together — thank you!
@@ -15,10 +15,10 @@ Gem::Specification.new do |gem|
15
15
  gem.summary = 'Couchbase ORM for Rails'
16
16
  gem.description = 'A Couchbase ORM for Rails'
17
17
 
18
- gem.required_ruby_version = '>= 2.7.0'
18
+ gem.required_ruby_version = '>= 3.1.0'
19
19
  gem.require_paths = ['lib']
20
20
 
21
- gem.add_runtime_dependency 'activemodel', ENV['ACTIVE_MODEL_VERSION'] || '>= 5.2'
21
+ gem.add_runtime_dependency 'activemodel', ENV['ACTIVE_MODEL_VERSION'] || '>= 7.1'
22
22
 
23
23
  gem.add_runtime_dependency 'couchbase', '>= 3.4.2'
24
24
  gem.add_runtime_dependency 'radix', '~> 2.2' # converting numbers to and from any base
@@ -0,0 +1,20 @@
1
+ # Dependencies
2
+ /node_modules
3
+
4
+ # Production
5
+ /build
6
+
7
+ # Generated files
8
+ .docusaurus
9
+ .cache-loader
10
+
11
+ # Misc
12
+ .DS_Store
13
+ .env.local
14
+ .env.development.local
15
+ .env.test.local
16
+ .env.production.local
17
+
18
+ npm-debug.log*
19
+ yarn-debug.log*
20
+ yarn-error.log*
@@ -0,0 +1,41 @@
1
+ # Website
2
+
3
+ This website is built using [Docusaurus](https://docusaurus.io/), a modern static website generator.
4
+
5
+ ### Installation
6
+
7
+ ```
8
+ $ yarn
9
+ ```
10
+
11
+ ### Local Development
12
+
13
+ ```
14
+ $ yarn start
15
+ ```
16
+
17
+ This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server.
18
+
19
+ ### Build
20
+
21
+ ```
22
+ $ yarn build
23
+ ```
24
+
25
+ This command generates static content into the `build` directory and can be served using any static contents hosting service.
26
+
27
+ ### Deployment
28
+
29
+ Using SSH:
30
+
31
+ ```
32
+ $ USE_SSH=true yarn deploy
33
+ ```
34
+
35
+ Not using SSH:
36
+
37
+ ```
38
+ $ GIT_USER=<Your GitHub username> yarn deploy
39
+ ```
40
+
41
+ If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.
@@ -0,0 +1,3 @@
1
+ module.exports = {
2
+ presets: [require.resolve('@docusaurus/core/lib/babel/preset')],
3
+ };
@@ -0,0 +1,49 @@
1
+ # Introduction
2
+
3
+ Welcome to the documentation for Couchbase ORM, an Object-Relational Mapping (ORM) library for Ruby that simplifies interactions with Couchbase Server. This guide will walk you through the features and usage of Couchbase ORM, helping you build efficient and scalable Ruby applications with Couchbase.
4
+
5
+ ## 1.1. What is Couchbase ORM?
6
+
7
+ Couchbase ORM is a Ruby library that provides an ActiveRecord-like interface for working with Couchbase Server, a highly scalable and performant NoSQL database. It allows you to define your application's data models as Ruby classes and interact with the database using a familiar and intuitive API.
8
+
9
+ With Couchbase ORM, you can:
10
+
11
+ - Define your data models and their relationships
12
+ - Perform CRUD (Create, Read, Update, Delete) operations on your models
13
+ - Query your data using a flexible and expressive query language
14
+ - Use Couchbase-specific features like N1QL queries and views
15
+ - Implement advanced features such as data validation, callbacks, and associations
16
+
17
+ Couchbase ORM abstracts away the low-level details of interacting with Couchbase Server, enabling you to focus on writing business logic and building great applications.
18
+
19
+ ## 1.2. Key Features
20
+
21
+ Couchbase ORM offers a wide range of features to make working with Couchbase Server a breeze. Some of the key features include:
22
+
23
+ 1. **ActiveModel Compliance**: Couchbase ORM follows the ActiveModel API, providing a familiar interface for developers who have worked with ActiveRecord or other ActiveModel-compliant libraries.
24
+
25
+ 2. **Attribute Definition**: Easily define your model's attributes and their types using a simple and intuitive DSL.
26
+
27
+ 3. **Querying**: Use a powerful and expressive query language to retrieve data from Couchbase Server. Couchbase ORM supports a wide range of query options, including filtering, ordering, limiting, and more.
28
+
29
+ 4. **Persistence**: Perform CRUD operations on your models with simple and intuitive methods like `save`, `create`, `update`, and `destroy`.
30
+
31
+ 5. **Associations**: Define relationships between your models, such as one-to-many and many-to-many, using simple declarations.
32
+
33
+ 6. **Validations**: Validate your model's data before persisting it to the database using a variety of built-in validators or custom validation methods.
34
+
35
+ 7. **Callbacks**: Define callbacks to execute code before or after certain events, such as saving or updating a model.
36
+
37
+ 8. **N1QL Queries**: Execute N1QL queries directly from your Ruby code and map the results to your models.
38
+
39
+ 9. **Views**: Create and query Couchbase views to efficiently retrieve data based on specific criteria.
40
+
41
+ 10. **Nested Documents**: Embed related documents within a parent document for denormalized data modeling.
42
+
43
+ These are just a few of the many features offered by Couchbase ORM. Throughout this documentation, we'll explore these features in-depth and provide examples of how to use them in your Ruby applications.
44
+
45
+ ## 1.3. Getting Started
46
+
47
+ To get started with Couchbase ORM, you'll need to have Ruby and Couchbase Server installed on your system. Once you have the prerequisites in place, you can install the Couchbase ORM gem and start building your application.
48
+
49
+ In the next section, we'll walk through the installation process and show you how to configure Couchbase ORM to connect to your Couchbase Server instance.
@@ -0,0 +1,108 @@
1
+ # Installation
2
+
3
+ Installing Couchbase ORM is a straightforward process. In this section, we'll guide you through the prerequisites and the step-by-step installation procedure.
4
+
5
+ ## 2.1. Prerequisites
6
+
7
+ Before installing Couchbase ORM, ensure that you have the following prerequisites in place:
8
+
9
+ 1. **Ruby**: Couchbase ORM requires Ruby version 2.7 or higher. You can check your Ruby version by running the following command in your terminal:
10
+
11
+ ```sh
12
+ ruby -v
13
+ ```
14
+
15
+ If you don't have Ruby installed or your version is older than 2.7, you can install the latest version from the official Ruby website: [https://www.ruby-lang.org](https://www.ruby-lang.org)
16
+
17
+ 2. **Couchbase Server**: Couchbase ORM works with Couchbase Server, a NoSQL database. Make sure you have Couchbase Server installed and running on your system. You can download Couchbase Server from the official website: [https://www.couchbase.com/downloads](https://www.couchbase.com/downloads)
18
+
19
+ Follow the installation instructions specific to your operating system to set up Couchbase Server.
20
+
21
+ 3. **Bundler** (optional): Bundler is a dependency management tool for Ruby. While not strictly required, it is recommended to use Bundler to manage your Ruby project's dependencies. You can install Bundler by running the following command:
22
+
23
+ ```sh
24
+ gem install bundler
25
+ ```
26
+
27
+ With these prerequisites in place, you're ready to install Couchbase ORM.
28
+
29
+ ## 2.2. Installing Couchbase ORM
30
+
31
+ To install Couchbase ORM, you have a couple of options:
32
+
33
+ 1. **Using Bundler** (recommended): If you're using Bundler to manage your project's dependencies, add the following line to your `Gemfile`:
34
+
35
+ ```ruby
36
+ gem 'couchbase-orm', git: 'https://github.com/Couchbase-Ecosystem/couchbase-ruby-orm'
37
+ ```
38
+
39
+ Then, run the following command to install the gem:
40
+
41
+ ```sh
42
+ bundle install
43
+ ```
44
+
45
+ Bundler will take care of installing Couchbase ORM and its dependencies.
46
+
47
+ 2. **Using RubyGems**: If you're not using Bundler, you can install Couchbase ORM directly using RubyGems. Run the following command in your terminal:
48
+
49
+ ```sh
50
+ gem install couchbase-orm
51
+ ```
52
+
53
+ This command will download and install the Couchbase ORM gem along with its dependencies.
54
+
55
+ After the installation is complete, you're ready to configure Couchbase ORM to connect to your Couchbase Server instance.
56
+
57
+ ## 2.3. Configuring Couchbase Connection
58
+
59
+ To use Couchbase ORM in your Ruby application, you need to configure the connection settings for your Couchbase Server instance. Couchbase ORM provides a simple way to configure the connection.
60
+
61
+ 1. **Rails Applications**:
62
+
63
+ If you're using Couchbase ORM in a Rails application, create a new configuration file named `couchbase.yml` in the `config` directory of your Rails project. Add the following content to the file:
64
+
65
+ ```yaml
66
+ development:
67
+ connection_string: couchbase://localhost
68
+ bucket: my_app_development
69
+ username: my_username
70
+ password: my_password
71
+
72
+ test:
73
+ connection_string: couchbase://localhost
74
+ bucket: my_app_test
75
+ username: my_username
76
+ password: my_password
77
+
78
+ production:
79
+ connection_string: <%= ENV['COUCHBASE_CONNECTION_STRING'] %>
80
+ bucket: <%= ENV['COUCHBASE_BUCKET'] %>
81
+ username: <%= ENV['COUCHBASE_USER'] %>
82
+ password: <%= ENV['COUCHBASE_PASSWORD'] %>
83
+ ```
84
+
85
+ Replace the values for `connection_string`, `bucket`, `username`, and `password` with your actual Couchbase Server connection details.
86
+
87
+ Couchbase ORM will automatically load the configuration based on the current Rails environment.
88
+
89
+ You can also set the connection details using environment variables in the production environment to avoid storing sensitive information in the source code.
90
+
91
+ 2. **Non-Rails Applications**:
92
+
93
+ For non-Rails applications, you can configure the connection settings programmatically. Add the following code to your application's initialization file or before you start using Couchbase ORM:
94
+
95
+ ```ruby
96
+ Couchbase ORM.configure do |config|
97
+ config.connection_string = 'couchbase://localhost'
98
+ config.bucket = 'travel-sample'
99
+ config.username = 'Administrator'
100
+ config.password = 'password'
101
+ end
102
+ ```
103
+
104
+ Replace the values for `connection_string`, `bucket`, `username`, and `password` with your actual Couchbase Server connection details.
105
+
106
+ With the connection configured, you're now ready to start defining your models and interacting with Couchbase Server using Couchbase ORM.
107
+
108
+ In the next section, we'll explore how to define models in Couchbase ORM and work with the basic CRUD operations.
@@ -0,0 +1,239 @@
1
+ # Defining Models
2
+
3
+ In CouchbaseOrm, models are defined as Ruby classes that inherit from `CouchbaseOrm::Base`. Each model represents a document type in Couchbase Server and encapsulates the data and behavior of the objects in your application.
4
+
5
+ ## 3.1. Creating a Model
6
+
7
+ To create a model, define a new class that inherits from `CouchbaseOrm::Base`. For example, let's create a `User` model:
8
+
9
+ ```ruby
10
+ class User < CouchbaseOrm::Base
11
+ end
12
+ ```
13
+
14
+ By convention, CouchbaseOrm uses the underscored, pluralized name of the class as the document type in Couchbase Server. In this case, the document type for the `User` model would be `users`.
15
+
16
+ ## 3.2. Attribute Types
17
+
18
+ CouchbaseOrm supports various attribute types to define the structure and types of your model's data. You can specify the attributes of your model using the `attribute` method.
19
+
20
+ Here's an example of defining attributes in the `User` model:
21
+
22
+ ```ruby
23
+ class User < CouchbaseOrm::Base
24
+ attribute :email, :string
25
+ attribute :name, :string
26
+ attribute :age, :integer
27
+ attribute :height, :float
28
+ attribute :is_active, :boolean
29
+ attribute :birth_date, :date
30
+ attribute :created_at, :datetime
31
+ attribute :updated_at, :datetime
32
+ attribute :appointment_time, :time
33
+ attribute :hobbies, :array, type: :string
34
+ attribute :metadata, type: Hash
35
+ attribute :avatar, :binary
36
+
37
+ attribute :created_at, :datetime
38
+ attribute :updated_at, :datetime
39
+ end
40
+ ```
41
+
42
+ In this example, we define several attributes for the `User` model, each with a specific type. The supported attribute types in CouchbaseOrm include:
43
+
44
+ - `:string`: Represents a string value.
45
+ - `:integer`: Represents an integer value.
46
+ - `:float`: Represents a floating-point value.
47
+ - `:boolean`: Represents a boolean value.
48
+ - `:date`: Represents a date value.
49
+ - `:datetime`: Represents a date and time value.
50
+ - `:time`: Represents a time value.
51
+ - `:array`: Represents an array of values.
52
+ - `:binary`: Represents a binary data value.
53
+
54
+ - `Hash`: Represents a hash (dictionary) of key-value pairs.
55
+
56
+ CouchbaseOrm automatically handles the serialization and deserialization of these attribute types when storing and retrieving documents from Couchbase Server.
57
+
58
+ ## 3.3. Attribute Options
59
+
60
+ In addition to specifying the attribute type, you can also provide additional options to customize the behavior of the attributes. Some commonly used options include:
61
+
62
+ - `default`: Specifies a default value for the attribute if no value is provided.
63
+
64
+
65
+ Here's an example of using attribute options:
66
+
67
+ ```ruby
68
+ class User < CouchbaseOrm::Base
69
+ attribute :name, :string, default: 'Unknown'
70
+ end
71
+ ```
72
+
73
+ In this example, the `name` attribute has a default value of `'Unknown'`.
74
+ <!-- the `email` attribute is aliased as `contact_email` in the document, and the `age` attribute is marked as read-only. -->
75
+
76
+ ## 3.4. Timestamps
77
+
78
+ CouchbaseOrm provides built-in support for timestamp attributes. By default, if you define attributes named `created_at` and `updated_at` with the `:datetime` type, CouchbaseOrm will automatically populate these attributes with the current date and time when a document is created or updated. To enable this feature, add the `created_at` and `updated_at` attributes to your model.The fields are automatically updated when the document is saved.`document.save`
79
+
80
+ ```ruby
81
+ class User < CouchbaseOrm::Base
82
+ attribute :created_at, :datetime
83
+ attribute :updated_at, :datetime
84
+ end
85
+ ```
86
+
87
+ With these timestamp attributes defined, CouchbaseOrm will manage them automatically whenever a document is persisted or updated.
88
+
89
+ ## 3.5. Callbacks
90
+
91
+ CouchbaseOrm supports lifecycle callbacks that allow you to execute code at certain points in a document's lifecycle. Callbacks can be used to perform actions before or after specific events, such as saving or updating a document.
92
+
93
+ Here are some commonly used callbacks:
94
+
95
+ - `before_create`: Runs before a new document is created.
96
+ - `after_create`: Runs after a new document is created.
97
+ - `before_save`: Runs before a document is saved (either created or updated).
98
+ - `after_save`: Runs after a document is saved (either created or updated).
99
+ - `before_update`: Runs before an existing document is updated.
100
+ - `after_update`: Runs after an existing document is updated.
101
+ - `before_destroy`: Runs before a document is destroyed.
102
+ - `after_destroy`: Runs after a document is destroyed.
103
+
104
+ To define a callback, use the corresponding callback method and provide a block or method name to be executed. For example:
105
+
106
+ ```ruby
107
+ class Document < CouchbaseOrm::Base
108
+ attribute :title, :string
109
+ attribute :content, :string
110
+
111
+ before_create :before_create_callback
112
+ after_create :after_create_callback
113
+ before_save :before_save_callback
114
+ after_save :after_save_callback
115
+ before_update :before_update_callback
116
+ after_update :after_update_callback
117
+ before_destroy :before_destroy_callback
118
+ after_destroy :after_destroy_callback
119
+
120
+ private
121
+
122
+ def before_create_callback
123
+ puts "Running before_create callback for #{title}"
124
+ end
125
+
126
+ def after_create_callback
127
+ puts "Running after_create callback for #{title}"
128
+ end
129
+
130
+ def before_save_callback
131
+ puts "Running before_save callback for #{title}"
132
+ end
133
+
134
+ def after_save_callback
135
+ puts "Running after_save callback for #{title}"
136
+ end
137
+
138
+ def before_update_callback
139
+ puts "Running before_update callback for #{title}"
140
+ end
141
+
142
+ def after_update_callback
143
+ puts "Running after_update callback for #{title}"
144
+ end
145
+
146
+ def before_destroy_callback
147
+ puts "Running before_destroy callback for #{title}"
148
+ end
149
+
150
+ def after_destroy_callback
151
+ puts "Running after_destroy callback for #{title}"
152
+ end
153
+ end
154
+ ```
155
+
156
+ In this example, the `Document` model defines several callbacks that are triggered at different points in the document's lifecycle. The callback methods are implemented as private instance methods within the model class.
157
+
158
+ Callbacks allow you to encapsulate logic related to the document lifecycle and maintain a clean and organized codebase.
159
+
160
+ ## 3.6. Validations
161
+
162
+ CouchbaseOrm includes built-in validation capabilities to ensure the integrity and validity of your data before persisting it to Couchbase Server. Validations help you enforce business rules and constraints on your models.
163
+
164
+ To define validations, use the `validates` method followed by the attribute name and the desired validation rules. For example:
165
+
166
+ ```ruby
167
+ class Book < CouchbaseOrm::Base
168
+ attribute :title, :string
169
+ attribute :author, :string
170
+ attribute :pages, :integer
171
+ attribute :genre, :string
172
+ attribute :email, :string
173
+
174
+ validates_presence_of :title
175
+ validates :author, presence: true
176
+ validates :pages, numericality: { greater_than: 0 }
177
+ validates :genre, inclusion: { in: %w[Fiction Non-Fiction] }
178
+ validates :author, format: { with: /\A[a-zA-Z]+\z/, message: 'only allows letters' }
179
+ validates :pages, length: { maximum: 500 }
180
+ validates :genre, exclusion: { in: %w[Science-Fiction] }
181
+ validates :email, format: { with: /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i }
182
+
183
+ validate :custom_validation
184
+
185
+ private
186
+
187
+ ...
188
+ end
189
+ ```
190
+
191
+ In this example, we define several validations for the `User` model:
192
+
193
+ - The `name` attribute must be present.
194
+ - The `email` attribute must match a specific format (a valid email address).
195
+ - The `age` attribute must be a number greater than or equal to 18.
196
+
197
+ CouchbaseOrm provides a wide range of built-in validation helpers, such as:
198
+
199
+ - `presence`: Ensures that the attribute is not blank.
200
+ - `validates_presence_of`: An alias for `presence`.
201
+ <!-- - `uniqueness`: Ensures that the attribute value is unique among all documents. -->
202
+ - `format`: Validates the attribute value against a regular expression.
203
+ - `length`: Validates the length of the attribute value.
204
+ - `numericality`: Validates that the attribute value is a valid number.
205
+ - `inclusion`: Ensures that the attribute value is included in a given set.
206
+ - `exclusion`: Ensures that the attribute value is not included in a given set.
207
+
208
+
209
+ You can also define custom validation methods by adding methods to your model class and using the `validate` method to trigger them. For example:
210
+
211
+ ```ruby
212
+ class Book < CouchbaseOrm::Base
213
+ attribute :title, :string
214
+ ...
215
+
216
+ validate :custom_validation
217
+
218
+ private
219
+
220
+ def custom_validation
221
+ puts 'Running custom validation...'
222
+ if title&.include?('Funny')
223
+ errors.add(:title, 'should not contain the word "Funny"')
224
+ else
225
+ # print the title
226
+ puts "Title: #{title}"
227
+ puts 'Custom validation passed'
228
+ end
229
+ end
230
+ end
231
+ ```
232
+
233
+ In this example, the `custom_validation` method is called during the validation process, and if `some_condition` is met, an error is added to the model's `errors` collection.
234
+
235
+ Validations are automatically run when saving a document. If any validations fail, the save operation will be aborted, and the model's `errors` collection will contain the validation error messages.
236
+
237
+ By leveraging validations, you can ensure the quality and consistency of your data before it is persisted to Couchbase Server.
238
+
239
+ With the model definition covered, including attributes, callbacks, and validations, you're ready to start querying and persisting data using CouchbaseOrm. In the next section, we'll explore the querying capabilities of CouchbaseOrm and how to retrieve data from Couchbase Server efficiently.