stretchy-model 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (49) hide show
  1. checksums.yaml +7 -0
  2. data/.rspec +1 -0
  3. data/.yardopts +1 -0
  4. data/CHANGELOG.md +5 -0
  5. data/CODE_OF_CONDUCT.md +84 -0
  6. data/Gemfile +10 -0
  7. data/LICENSE.txt +21 -0
  8. data/README.md +146 -0
  9. data/Rakefile +4 -0
  10. data/containers/Dockerfile.elasticsearch +7 -0
  11. data/containers/Dockerfile.opensearch +19 -0
  12. data/docker-compose.yml +52 -0
  13. data/lib/active_model/type/array.rb +13 -0
  14. data/lib/active_model/type/hash.rb +15 -0
  15. data/lib/rails/instrumentation/publishers.rb +29 -0
  16. data/lib/rails/instrumentation/railtie.rb +29 -0
  17. data/lib/stretchy/associations/associated_validator.rb +17 -0
  18. data/lib/stretchy/associations/elastic_relation.rb +38 -0
  19. data/lib/stretchy/associations.rb +161 -0
  20. data/lib/stretchy/common.rb +33 -0
  21. data/lib/stretchy/delegation/delegate_cache.rb +131 -0
  22. data/lib/stretchy/delegation/gateway_delegation.rb +43 -0
  23. data/lib/stretchy/indexing/bulk.rb +48 -0
  24. data/lib/stretchy/model/callbacks.rb +31 -0
  25. data/lib/stretchy/model/serialization.rb +20 -0
  26. data/lib/stretchy/null_relation.rb +53 -0
  27. data/lib/stretchy/persistence.rb +43 -0
  28. data/lib/stretchy/querying.rb +20 -0
  29. data/lib/stretchy/record.rb +57 -0
  30. data/lib/stretchy/refreshable.rb +15 -0
  31. data/lib/stretchy/relation.rb +169 -0
  32. data/lib/stretchy/relations/finder_methods.rb +39 -0
  33. data/lib/stretchy/relations/merger.rb +179 -0
  34. data/lib/stretchy/relations/query_builder.rb +265 -0
  35. data/lib/stretchy/relations/query_methods.rb +578 -0
  36. data/lib/stretchy/relations/search_option_methods.rb +34 -0
  37. data/lib/stretchy/relations/spawn_methods.rb +60 -0
  38. data/lib/stretchy/repository.rb +10 -0
  39. data/lib/stretchy/scoping/default.rb +134 -0
  40. data/lib/stretchy/scoping/named.rb +68 -0
  41. data/lib/stretchy/scoping/scope_registry.rb +34 -0
  42. data/lib/stretchy/scoping.rb +28 -0
  43. data/lib/stretchy/shared_scopes.rb +34 -0
  44. data/lib/stretchy/utils.rb +69 -0
  45. data/lib/stretchy/version.rb +5 -0
  46. data/lib/stretchy.rb +38 -0
  47. data/sig/stretchy.rbs +4 -0
  48. data/stretchy.logo.png +0 -0
  49. metadata +247 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: a955580b683d3dc991c7a1f92a5a9508fd10a4f9e8a116c2c92150ae4fdd43a3
4
+ data.tar.gz: 30262c4a0d4e8d5e43a74ab707b3e501d8e5e627be16600687526885b4520cf3
5
+ SHA512:
6
+ metadata.gz: ce944998d1e6ae225f85fa7ecbccea8f940e3fcee99c8450b79f89b3138bedcddec7b69d62de8285983c21dbc4dc068c4fa42157d94484065a8948c118c9bd95
7
+ data.tar.gz: 465d02c93b645b480bc4e627d4323d557ab6574dbefc2efc83de453aa246d38785ccb09cebf8d651e3f345d68e851e1197f32314bec84d13a379320dc468c3eb
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --require spec_helper
data/.yardopts ADDED
@@ -0,0 +1 @@
1
+ --markup markdown
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-02-26
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at spencer@theablefew.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in stretchy.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Spencer Markowski
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,146 @@
1
+ stretchy
2
+ ===
3
+
4
+ <p>
5
+ <a href="https://stretchy.io/" target="_blank"><img src="./stretchy.logo.png" alt="Gum Image" width="450" /></a>
6
+ <br><br>
7
+ <a href="https://github.com/theablefew/stretchy/releases"><img src="https://img.shields.io/github/v/release/theablefew/stretchy?sort=semver&color=blue"></a>
8
+ <a href="https://github.com/theablefew/stretchy/actions"><img src="https://github.com/theablefew/stretchy/actions/workflows/spec.yml/badge.svg"></a>
9
+
10
+ </p>
11
+
12
+ Stretchy provides Elasticsearch models in a Rails environment with an integrated ActiveRecord-like interface and features.
13
+
14
+ ## Features
15
+ Stretchy simplifies the process of querying, aggregating, and managing Elasticsearch-backed models, allowing Rails developers to work with search indices as comfortably as they would with traditional Rails models.
16
+
17
+ ## Attributes
18
+
19
+ ```ruby
20
+ class Post < Stretchy::Record
21
+
22
+ attribute :title, :string
23
+ attribute :body, :string
24
+ attribute :flagged, :boolean, default: false
25
+ attribute :author, :hash
26
+ attribute :tags, :array, default: []
27
+
28
+ end
29
+ ```
30
+ >[!NOTE]
31
+ >`created_at`, `:updated_at` and `:id` are automatically added to all `Stretchy::Records`
32
+
33
+
34
+ ## Query
35
+ ```ruby
36
+ Post.where('author.name': "Jadzia", flagged: true).first
37
+ #=> <Post id: aW02w3092, title: "Fun Cats", body: "...", flagged: true,
38
+ # author: {name: "Jadzia", age: 20}, tags: ["cat", "amusing"]>
39
+ ```
40
+
41
+ ## Aggregations
42
+ ```ruby
43
+
44
+ result = Post.filter(:range, 'author.age': {gte: 18})
45
+ .aggregation(:post_frequency, date_histogram: {
46
+ field: :created_at,
47
+ calender_interval: :month
48
+ })
49
+
50
+ result.aggregations.post_frequency
51
+ #=> {buckets: [{key_as_string: "2024-01-01", doc_count: 20}, ...]}
52
+ ```
53
+
54
+ ## Scopes
55
+
56
+ ```ruby
57
+ class Post < Stretchy::Record
58
+ # ...attributes
59
+
60
+ # Scopes
61
+ scope :flagged, -> { where(flagged: true) }
62
+ scope :top_links, lambda do |size=10, url=".com"|
63
+ aggregation(:links,
64
+ terms: {
65
+ field: :links,
66
+ size: size,
67
+ include: ".*#{url}.*"
68
+ })
69
+ end
70
+ end
71
+
72
+ # Returns flagged posts and includes the top 10 'youtube.com'
73
+ # links in results.aggregations.links
74
+ result = Post.flagged.top_links(10, "youtube.com")
75
+
76
+ ```
77
+
78
+ ## Bulk Operations
79
+
80
+
81
+ ```ruby
82
+ Model.bulk(records_as_bulk_operations)
83
+ ```
84
+
85
+ #### Bulk helper
86
+ Generates structure for the bulk operation
87
+ ```ruby
88
+ record.to_bulk # default to_bulk(:index)
89
+ record.to_bulk(:delete)
90
+ record.to_bulk(:update)
91
+ ```
92
+
93
+ #### In batches
94
+ Run bulk operations in batches specified by `size`
95
+ ```ruby
96
+ Model.bulk_in_batches(records, size: 100) do |batch|
97
+ batch.map! { |record| Model.new(record).to_bulk }
98
+ end
99
+ ```
100
+
101
+
102
+ ## Instrumentation
103
+ ```ruby
104
+ Blanket.first
105
+ ```
106
+
107
+ ```sh
108
+ Blanket (6.322ms) curl -X GET 'http://localhost:9200/blankets/_search?size=1' -d '{"sort":{"date":"desc"}}'
109
+ ```
110
+
111
+ ## Installation
112
+
113
+ Install the gem and add to the application's Gemfile by executing:
114
+
115
+ $ bundle add stretchy
116
+
117
+ If bundler is not being used to manage dependencies, install the gem by executing:
118
+
119
+ $ gem install stretchy
120
+
121
+ ## Development
122
+
123
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
124
+
125
+ >[!TIP]
126
+ >This library is built on top of the excellent [elasticsearch-persistence](https://github.com/elastic/elasticsearch-rails/tree/main/elasticsearch-persistence) gem.
127
+ >
128
+ > Full documentation on [Elasticsearch Query DSL and Aggregation options](https://github.com/elastic/elasticsearch-rails/tree/main/elasticsearch-persistence)
129
+
130
+ ## Testing
131
+ ```
132
+ docker-compose up elasticsearch
133
+ ```
134
+
135
+ ```
136
+ bundle exec rspec
137
+ ```
138
+
139
+ ## Contributing
140
+
141
+ Bug reports and pull requests are welcome on GitHub at https://github.com/theablefew/stretchy. 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/theablefew/stretchy/blob/master/CODE_OF_CONDUCT.md).
142
+
143
+ ## License
144
+
145
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
146
+
data/Rakefile ADDED
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ task default: %i[]
@@ -0,0 +1,7 @@
1
+ # Dockerfile.elasticsearch
2
+
3
+ # Base image
4
+ FROM docker.elastic.co/elasticsearch/elasticsearch:7.10.1
5
+
6
+ # Environment variables
7
+ ENV discovery.type=single-node
@@ -0,0 +1,19 @@
1
+ # Dockerfile.opensearch
2
+
3
+ # Base image
4
+ FROM opensearchproject/opensearch:2.12.0
5
+
6
+ # Environment variables
7
+ # disables bootstrap checks that are enabled when network.host is set to a non-loopback address
8
+ ENV discovery.type=single-node
9
+ # ENV cluster.name=opensearch-cluster
10
+ ENV node.name=opensearch-node1
11
+ ENV plugins.security.disabled=true
12
+ # along with the memlock settings below, disables swapping
13
+ ENV bootstrap.memory_lock=true
14
+ # minimum and maximum Java heap size, recommend setting both to 50% of system RAM
15
+ ENV OPENSEARCH_JAVA_OPTS="-Xms512m -Xmx512m"
16
+ # disables execution of install_demo_configuration.sh bundled with security plugin, which installs demo certificates and security configurations to OpenSearch
17
+ ENV DISABLE_INSTALL_DEMO_CONFIG=true
18
+ # disables security plugin entirely in OpenSearch by setting plugins.security.disabled: true in opensearch.yml
19
+ ENV DISABLE_SECURITY_PLUGIN=true
@@ -0,0 +1,52 @@
1
+ # docker-compose.yml
2
+
3
+ version: '3'
4
+ services:
5
+ elasticsearch:
6
+ build:
7
+ context: .
8
+ dockerfile: containers/Dockerfile.elasticsearch
9
+ ports:
10
+ - "9200:9200"
11
+ environment:
12
+ - discovery.type=single-node
13
+
14
+ opensearch:
15
+ build:
16
+ context: .
17
+ dockerfile: containers/Dockerfile.opensearch
18
+ ulimits:
19
+ memlock:
20
+ soft: -1
21
+ hard: -1
22
+ nofile:
23
+ soft: 65536 # maximum number of open files for the OpenSearch user, set to at least 65536 on modern systems
24
+ hard: 65536
25
+ environment:
26
+ - discovery.type=single-node
27
+ # volumes:
28
+ # - opensearch-data1:/usr/share/opensearch/data
29
+ ports:
30
+ - 9200:9200
31
+ - 9600:9600 # required for Performance Analyzer
32
+ # networks:
33
+ # - opensearch-net
34
+
35
+ # opensearch-dashboards:
36
+ # image: opensearchproject/opensearch-dashboards:1.2.0
37
+ # container_name: opensearch-dashboards
38
+ # ports:
39
+ # - 5601:5601
40
+ # expose:
41
+ # - "5601"
42
+ # environment:
43
+ # - 'OPENSEARCH_HOSTS=["http://opensearch-node1:9200"]'
44
+ # - "DISABLE_SECURITY_DASHBOARDS_PLUGIN=true" # disables security dashboards plugin in OpenSearch Dashboards
45
+ # networks:
46
+ # - opensearch-net
47
+
48
+ # volumes:
49
+ # opensearch-data1:
50
+
51
+ # networks:
52
+ # opensearch-net:
@@ -0,0 +1,13 @@
1
+ module ActiveModel
2
+ module Type
3
+
4
+ class Array < Value # :nodoc:
5
+
6
+ def type
7
+ :array
8
+ end
9
+
10
+ end
11
+
12
+ end
13
+ end
@@ -0,0 +1,15 @@
1
+ module ActiveModel
2
+ module Type
3
+ class Hash < Value # :nodoc:
4
+ def type
5
+ :hash
6
+ end
7
+
8
+ private
9
+
10
+ def cast_value(value)
11
+ Elasticsearch::Model::HashWrapper[value]
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,29 @@
1
+ module Rails
2
+ module Instrumentation
3
+ module Publishers
4
+
5
+ module Record
6
+
7
+ extend ActiveSupport::Concern
8
+
9
+ included do
10
+ unless method_defined?(:search_without_instrumentation!)
11
+ alias_method :search_without_instrumentation!, :search
12
+ alias_method :search, :search_with_instrumentation!
13
+ end
14
+ end
15
+
16
+ def search_with_instrumentation!(query_or_definition, options={})
17
+ ActiveSupport::Notifications.instrument "search.elasticsearch",
18
+ name: "Search",
19
+ klass: self.base_class.to_s,
20
+ search: {index: self.index_name, body: query_or_definition }.merge(options) do
21
+ search_without_instrumentation!(query_or_definition, options)
22
+ end
23
+ end
24
+
25
+ end
26
+
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,29 @@
1
+ module Stretchy
2
+ module Instrumentation
3
+
4
+ class Railtie < ::Rails::Railtie
5
+ include ActionView::Helpers::NumberHelper
6
+ def time_diff(start, finish)
7
+ begin
8
+ ((finish.to_time - start.to_time) * 1000).to_s(:rounded, precision: 5, strip_insignificant_zeros: true)
9
+ rescue
10
+ number_with_precision((finish.to_time - start.to_time) * 1000, precision: 5, strip_insignificant_zeros: true)
11
+ end
12
+ end
13
+
14
+ ActiveSupport::Notifications.subscribe 'query.elasticsearch' do |name, start, finish, id, payload|
15
+ ::Rails.logger.debug([" #{payload[:name]}".bright, "(#{time_diff(start,finish)}ms)",payload[:query]].join(" ").color(:yellow))
16
+ end
17
+
18
+ ActiveSupport::Notifications.subscribe 'cache.query.elasticsearch' do |name, start, finish, id, payload|
19
+ ::Rails.logger.debug([" #{payload[:name]}".bright, "CACHE".color(:mediumpurple).bright ,"(#{time_diff(start,finish)}ms)", payload[:query]].join(" ").color(:yellow))
20
+ end
21
+
22
+ initializer 'stretchy.set_defaults' do
23
+ config.elasticsearch_cache_store = :redis_store
24
+ config.elasticsearch_expire_cache_in = 15.minutes
25
+ end
26
+
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,17 @@
1
+ module Stretchy
2
+ module Associations
3
+ class AssociatedValidator < ActiveModel::EachValidator #:nodoc:
4
+ def validate_each(record, attribute, value)
5
+ if Array(value).reject { |r| valid_object?(r) }.any?
6
+ record.errors.add(attribute, :invalid, options.merge(value: value))
7
+ end
8
+ end
9
+
10
+ private
11
+
12
+ def valid_object?(record)
13
+ record.valid?
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,38 @@
1
+ module Stretchy
2
+ module Associations
3
+ class ElasticRelation
4
+ delegate :blank?, :empty?, :any?, :many?, :first, :last, to: :results
5
+ delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to_ary, :join, to: :to_a
6
+
7
+ attr_reader :klass
8
+ alias :model :klass
9
+
10
+ def initialize(klass, records = [], collection = true)
11
+ @klass = klass
12
+ @records = records
13
+ @collection = collection
14
+ end
15
+
16
+ def build(*args)
17
+ r = @klass.new(*args)
18
+ @records << r
19
+ r
20
+ end
21
+
22
+ def delete(opts = nil)
23
+ dr = @records.delete_if { |r| r === opts }
24
+ dr.first
25
+ end
26
+
27
+ def to_a
28
+ @records
29
+ end
30
+
31
+ alias :results :to_a
32
+
33
+ def collection?
34
+ @collection
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,161 @@
1
+ module Stretchy
2
+ module Associations
3
+ extend ActiveSupport::Concern
4
+
5
+ def save!
6
+ self.save
7
+ end
8
+
9
+ # Required for Elasticsearch < 7
10
+ def type
11
+ "_doc"
12
+ end
13
+
14
+ def _type
15
+ "_doc"
16
+ end
17
+
18
+ def new_record?
19
+ self.id.nil?
20
+ end
21
+
22
+ def marked_for_destruction?
23
+ _destroy
24
+ end
25
+
26
+ def after_save_objects(s, association)
27
+ @_after_save_objects ||= {}
28
+ @_after_save_objects[association] ||= []
29
+ @_after_save_objects[association] << self.send("build_#{association}", s)
30
+ end
31
+
32
+ def dirty
33
+ @_after_save_objects || {}
34
+ end
35
+
36
+ def association_reflection(association)
37
+ ElasticRelation.new @@_associations[association], (dirty[association.to_sym] || [])
38
+ end
39
+
40
+ def _destroy=(bool)
41
+ @_destroy = bool
42
+ end
43
+
44
+ def _destroy
45
+ return @_destroy
46
+ end
47
+
48
+ def save_associations
49
+ @_after_save_objects.each_pair do |association, collection|
50
+ collection.each do |instance|
51
+ instance.send("#{@@_association_options[association.to_sym][:foreign_key]}=", self.id)
52
+ instance.save
53
+ end
54
+ end unless @_after_save_objects.nil?
55
+ @_after_save_objects = {}
56
+ end
57
+
58
+ class_methods do
59
+ @@_associations ||= {}
60
+ @@_association_options ||= {}
61
+
62
+ def belongs_to(association, options = {})
63
+ @@_association_options[association] = {
64
+ foreign_key: "#{association}_id",
65
+ primary_key: "id",
66
+ class_name: association
67
+ }.reverse_merge(options)
68
+
69
+ klass = @@_association_options[association][:class_name].to_s.singularize.classify.constantize
70
+ @@_associations[association] = klass
71
+
72
+ define_method(association.to_sym) do
73
+ klass.where(_id: self.send(@@_association_options[association][:foreign_key].to_sym)).first
74
+ end
75
+
76
+ define_method("#{association}=".to_sym) do |val|
77
+ options = @@_association_options[association]
78
+ instance_variable_set("@#{options[:foreign_key]}", val.send(options[:primary_key]))
79
+ end
80
+ end
81
+
82
+ def has_one(association, class_name: nil, foreign_key: nil, dependent: :destroy)
83
+
84
+ klass = association.to_s.singularize.classify.constantize unless class_name.present?
85
+ foreign_key = "#{self.name.downcase}_id" unless foreign_key.present?
86
+ @@_associations[association] = klass
87
+
88
+ define_method(association.to_sym) do
89
+ klass.where("#{foreign_key}": self.id).first
90
+ end
91
+ end
92
+
93
+ def has_many(association, klass, options = {})
94
+ @@_associations[association] = klass
95
+
96
+ opt_fk = options.delete(:foreign_key)
97
+ foreign_key = opt_fk ? opt_fk : "#{self.name.split("::").last.tableize.singularize}_id"
98
+
99
+ @@_association_options[association] = { foreign_key: foreign_key }
100
+
101
+ define_method(association.to_sym) do
102
+ args = {}
103
+ args[foreign_key] = self.id
104
+ self.new_record? ? association_reflection(association) : klass.where(args)
105
+ end
106
+
107
+ define_method("build_#{association}".to_sym) do |*args|
108
+ opts = {}
109
+ opts[foreign_key] = self.id
110
+ args.first.merge! opts
111
+ klass.new *args
112
+ end
113
+ end
114
+
115
+ def validates_associated(*attr_names)
116
+ validates_with AssociatedValidator, _merge_attributes(attr_names)
117
+ end
118
+
119
+ def accepts_nested_attributes_for(association)
120
+ after_create :save_associations
121
+
122
+ define_method("#{association}_attributes=".to_sym) do |*args|
123
+ args.each do |key|
124
+ key.values.each do |instance|
125
+ self.after_save_objects(instance, association)
126
+ end
127
+ end
128
+
129
+ association_reflection(association)
130
+ end
131
+ end
132
+
133
+ def reflect_on_association(association)
134
+ ElasticRelation.new @@_associations[association]
135
+ end
136
+
137
+ def update_all(records, **attributes)
138
+
139
+ records.map do |record|
140
+ attributes.each { |key, value| record.send("#{key}=", value) }
141
+ record
142
+ end.each_slice(100) do |batch|
143
+ update_batch = batch.collect{ |m| m.to_bulk(:update)}
144
+ self.gateway.client.bulk body: update_batch
145
+ end
146
+
147
+ self.refresh_index
148
+ records
149
+
150
+ end
151
+
152
+ def association_names
153
+ @@_associations.keys
154
+ end
155
+
156
+ def find_or_create_by(**args)
157
+ self.where(args).first || self.create(args)
158
+ end
159
+ end
160
+ end
161
+ end