all_futures 1.0.3 → 2.0.0

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 (106) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile +4 -1
  3. data/Gemfile.lock +272 -61
  4. data/LICENSE.txt +1 -1
  5. data/README.md +59 -79
  6. data/Rakefile +13 -1
  7. data/SUMMARY.md +22 -2
  8. data/bin/console +8 -0
  9. data/bin/loc +0 -0
  10. data/bin/setup +0 -0
  11. data/bin/standardize +0 -0
  12. data/lib/all_futures/association.rb +42 -0
  13. data/lib/all_futures/association_index.rb +69 -0
  14. data/lib/all_futures/attributes.rb +28 -0
  15. data/lib/all_futures/base.rb +66 -0
  16. data/lib/all_futures/callbacks.rb +71 -0
  17. data/lib/all_futures/configuration.rb +9 -0
  18. data/lib/all_futures/dirty.rb +116 -0
  19. data/lib/all_futures/embeds.rb +40 -0
  20. data/lib/all_futures/errors.rb +37 -0
  21. data/lib/all_futures/finder.rb +214 -0
  22. data/lib/all_futures/locale/en.yml +49 -0
  23. data/lib/all_futures/persistence.rb +595 -0
  24. data/lib/all_futures/presenter.rb +35 -0
  25. data/lib/all_futures/railtie.rb +26 -0
  26. data/lib/all_futures/translation.rb +22 -0
  27. data/lib/all_futures/validations.rb +10 -0
  28. data/lib/all_futures/version.rb +3 -1
  29. data/lib/all_futures/versions.rb +80 -0
  30. data/lib/all_futures.rb +24 -1
  31. data/lib/vendor/ACTIVE_ENTITY_MIT-LICENSE +42 -0
  32. data/lib/vendor/README.md +8 -0
  33. data/lib/vendor/active_entity/aggregations.rb +277 -0
  34. data/lib/vendor/active_entity/associations/embeds/association.rb +134 -0
  35. data/lib/vendor/active_entity/associations/embeds/builder/association.rb +105 -0
  36. data/lib/vendor/active_entity/associations/embeds/builder/collection_association.rb +71 -0
  37. data/lib/vendor/active_entity/associations/embeds/builder/embedded_in.rb +38 -0
  38. data/lib/vendor/active_entity/associations/embeds/builder/embeds_many.rb +13 -0
  39. data/lib/vendor/active_entity/associations/embeds/builder/embeds_one.rb +16 -0
  40. data/lib/vendor/active_entity/associations/embeds/builder/singular_association.rb +28 -0
  41. data/lib/vendor/active_entity/associations/embeds/collection_association.rb +209 -0
  42. data/lib/vendor/active_entity/associations/embeds/collection_proxy.rb +310 -0
  43. data/lib/vendor/active_entity/associations/embeds/embedded_in_association.rb +31 -0
  44. data/lib/vendor/active_entity/associations/embeds/embeds_many_association.rb +15 -0
  45. data/lib/vendor/active_entity/associations/embeds/embeds_one_association.rb +26 -0
  46. data/lib/vendor/active_entity/associations/embeds/singular_association.rb +35 -0
  47. data/lib/vendor/active_entity/associations.rb +168 -0
  48. data/lib/vendor/active_entity/attribute_assignment.rb +87 -0
  49. data/lib/vendor/active_entity/attribute_decorators.rb +90 -0
  50. data/lib/vendor/active_entity/attribute_methods/before_type_cast.rb +78 -0
  51. data/lib/vendor/active_entity/attribute_methods/dirty.rb +180 -0
  52. data/lib/vendor/active_entity/attribute_methods/primary_key.rb +96 -0
  53. data/lib/vendor/active_entity/attribute_methods/query.rb +38 -0
  54. data/lib/vendor/active_entity/attribute_methods/read.rb +44 -0
  55. data/lib/vendor/active_entity/attribute_methods/serialization.rb +90 -0
  56. data/lib/vendor/active_entity/attribute_methods/time_zone_conversion.rb +93 -0
  57. data/lib/vendor/active_entity/attribute_methods/write.rb +54 -0
  58. data/lib/vendor/active_entity/attribute_methods.rb +833 -0
  59. data/lib/vendor/active_entity/attributes.rb +240 -0
  60. data/lib/vendor/active_entity/base.rb +293 -0
  61. data/lib/vendor/active_entity/callbacks.rb +21 -0
  62. data/lib/vendor/active_entity/coders/json.rb +15 -0
  63. data/lib/vendor/active_entity/coders/yaml_column.rb +50 -0
  64. data/lib/vendor/active_entity/core.rb +348 -0
  65. data/lib/vendor/active_entity/enum.rb +260 -0
  66. data/lib/vendor/active_entity/errors.rb +69 -0
  67. data/lib/vendor/active_entity/gem_version.rb +17 -0
  68. data/lib/vendor/active_entity/inheritance.rb +176 -0
  69. data/lib/vendor/active_entity/integration.rb +78 -0
  70. data/lib/vendor/active_entity/locale/en.yml +45 -0
  71. data/lib/vendor/active_entity/model_schema.rb +118 -0
  72. data/lib/vendor/active_entity/nested_attributes.rb +554 -0
  73. data/lib/vendor/active_entity/persistence.rb +20 -0
  74. data/lib/vendor/active_entity/railtie.rb +76 -0
  75. data/lib/vendor/active_entity/readonly_attributes.rb +55 -0
  76. data/lib/vendor/active_entity/reflection.rb +447 -0
  77. data/lib/vendor/active_entity/serialization.rb +28 -0
  78. data/lib/vendor/active_entity/store.rb +291 -0
  79. data/lib/vendor/active_entity/translation.rb +24 -0
  80. data/lib/vendor/active_entity/type/date.rb +9 -0
  81. data/lib/vendor/active_entity/type/date_time.rb +9 -0
  82. data/lib/vendor/active_entity/type/internal/timezone.rb +17 -0
  83. data/lib/vendor/active_entity/type/json.rb +30 -0
  84. data/lib/vendor/active_entity/type/modifiers/array.rb +72 -0
  85. data/lib/vendor/active_entity/type/modifiers/array_without_blank.rb +19 -0
  86. data/lib/vendor/active_entity/type/registry.rb +112 -0
  87. data/lib/vendor/active_entity/type/serialized.rb +71 -0
  88. data/lib/vendor/active_entity/type/text.rb +11 -0
  89. data/lib/vendor/active_entity/type/time.rb +21 -0
  90. data/lib/vendor/active_entity/type/unsigned_integer.rb +17 -0
  91. data/lib/vendor/active_entity/type.rb +75 -0
  92. data/lib/vendor/active_entity/validate_embeds_association.rb +300 -0
  93. data/lib/vendor/active_entity/validations/absence.rb +25 -0
  94. data/lib/vendor/active_entity/validations/associated.rb +60 -0
  95. data/lib/vendor/active_entity/validations/length.rb +26 -0
  96. data/lib/vendor/active_entity/validations/presence.rb +68 -0
  97. data/lib/vendor/active_entity/validations/subset.rb +76 -0
  98. data/lib/vendor/active_entity/validations/uniqueness_in_embeds.rb +91 -0
  99. data/lib/vendor/active_entity/validations/uniqueness_on_active_record.rb +234 -0
  100. data/lib/vendor/active_entity/validations.rb +47 -0
  101. data/lib/vendor/active_entity/version.rb +10 -0
  102. data/lib/vendor/active_entity.rb +99 -0
  103. data/lib/vendor/core_ext/array_without_blank.rb +48 -0
  104. metadata +175 -21
  105. data/lib/all_futures/all_futures.rb +0 -28
  106. data/lib/all_futures/config.rb +0 -14
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AllFutures
4
+ module Versions
5
+ extend ActiveSupport::Concern
6
+
7
+ Version = Struct.new(:attributes, :updated_at) do
8
+ def to_h
9
+ attributes
10
+ end
11
+
12
+ def inspect
13
+ attributes
14
+ end
15
+
16
+ def reject
17
+ attributes
18
+ end
19
+ end
20
+
21
+ included do
22
+ class_attribute :versioning, instance_accessor: false, default: false
23
+ end
24
+
25
+ def current_version
26
+ @_current_version&.to_i
27
+ end
28
+
29
+ def disable_versioning!
30
+ @_versioning_enabled = false
31
+ end
32
+
33
+ def enable_versioning!
34
+ @_versioning_enabled = true
35
+ end
36
+
37
+ def version(index)
38
+ _raise_version_not_found(index) unless versions.key?(index)
39
+ updated_at = versions[index]["updated_at"]
40
+ updated_at = updated_at.is_a?(ActiveSupport::TimeWithZone) ? updated_at : Time.zone.parse(updated_at)
41
+ Version.new(versions[index]["attributes"], updated_at)
42
+ end
43
+
44
+ def versions
45
+ @_versions
46
+ end
47
+
48
+ def without_versioning
49
+ return unless block_given?
50
+
51
+ disable_versioning!
52
+ yield self
53
+ enable_versioning!
54
+
55
+ self
56
+ end
57
+
58
+ def versioning_enabled?
59
+ @_versioning_enabled
60
+ end
61
+
62
+ private
63
+
64
+ def _raise_version_not_found(index)
65
+ raise AllFutures::VersionNotFound, "Could not find version #{index}"
66
+ end
67
+
68
+ module ClassMethods
69
+ def enable_versioning!
70
+ self.versioning = true
71
+ end
72
+
73
+ def load_versions(model, record)
74
+ return if record["versions"].nil?
75
+ model.instance_variable_set :@_current_version, record["current_version"]
76
+ model.instance_variable_set :@_versions, record["versions"].transform_keys(&:to_i)
77
+ end
78
+ end
79
+ end
80
+ end
data/lib/all_futures.rb CHANGED
@@ -1,5 +1,28 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ # Active Entity is vendored under lib/vendor (abandoned upstream; we maintain the fork).
4
+ vendor = File.expand_path("vendor", __dir__)
5
+ $LOAD_PATH.unshift(vendor) unless $LOAD_PATH.include?(vendor)
6
+
3
7
  require "active_entity/railtie"
8
+ require "active_record" # for ActiveRecord::Integration (cache keys) and ActiveRecord::Base checks; internals can't be cherry-picked since Rails 7.1
9
+ require "kredis"
10
+ require "ulid"
11
+ require "all_futures/configuration"
12
+ require "all_futures/association_index"
13
+ require "all_futures/association"
14
+ require "all_futures/attributes"
15
+ require "all_futures/callbacks"
16
+ require "all_futures/dirty"
17
+ require "all_futures/embeds"
18
+ require "all_futures/errors"
19
+ require "all_futures/finder"
20
+ require "all_futures/persistence"
21
+ require "all_futures/presenter"
22
+ require "all_futures/translation"
23
+ require "all_futures/validations"
4
24
  require "all_futures/version"
5
- require "all_futures/all_futures"
25
+ require "all_futures/versions"
26
+ require "all_futures/base"
27
+
28
+ require "all_futures/railtie" if defined?(Rails::Railtie)
@@ -0,0 +1,42 @@
1
+ Copyright (c) 2020 jasl
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+
23
+ Copyright (c) 2005-2019 David Heinemeier Hansson
24
+
25
+ Permission is hereby granted, free of charge, to any person obtaining
26
+ a copy of this software and associated documentation files (the
27
+ "Software"), to deal in the Software without restriction, including
28
+ without limitation the rights to use, copy, modify, merge, publish,
29
+ distribute, sublicense, and/or sell copies of the Software, and to
30
+ permit persons to whom the Software is furnished to do so, subject to
31
+ the following conditions:
32
+
33
+ The above copyright notice and this permission notice shall be
34
+ included in all copies or substantial portions of the Software.
35
+
36
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
37
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
38
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
39
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
40
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
41
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
42
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,8 @@
1
+ # Vendored Active Entity
2
+ #
3
+ # Active Entity (https://github.com/jasl/activeentity) is abandoned upstream.
4
+ # The library is vendored here under MIT (see ACTIVE_ENTITY_MIT-LICENSE) so
5
+ # All Futures can ship without a path: or rubygems dependency on a dead gem.
6
+ #
7
+ # Source of this tree: leastbad/activeentity @ rails-8-compat (mutex_m removed
8
+ # for Ruby 3.4, Rails dependency cap lifted to < 9).
@@ -0,0 +1,277 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveEntity
4
+ # See ActiveEntity::Aggregations::ClassMethods for documentation
5
+ module Aggregations
6
+ def initialize_dup(*) # :nodoc:
7
+ @aggregation_cache = {}
8
+ super
9
+ end
10
+
11
+ private
12
+
13
+ def init_internals
14
+ @aggregation_cache = {}
15
+ super
16
+ end
17
+
18
+ # Active Entity implements aggregation through a macro-like class method called #composed_of
19
+ # for representing attributes as value objects. It expresses relationships like "Account [is]
20
+ # composed of Money [among other things]" or "Person [is] composed of [an] address". Each call
21
+ # to the macro adds a description of how the value objects are created from the attributes of
22
+ # the entity object (when the entity is initialized either as a new object or from finding an
23
+ # existing object) and how it can be turned back into attributes (when the entity is saved to
24
+ # the database).
25
+ #
26
+ # class Customer < ActiveEntity::Base
27
+ # composed_of :balance, class_name: "Money", mapping: %w(balance amount)
28
+ # composed_of :address, mapping: [ %w(address_street street), %w(address_city city) ]
29
+ # end
30
+ #
31
+ # The customer class now has the following methods to manipulate the value objects:
32
+ # * <tt>Customer#balance, Customer#balance=(money)</tt>
33
+ # * <tt>Customer#address, Customer#address=(address)</tt>
34
+ #
35
+ # These methods will operate with value objects like the ones described below:
36
+ #
37
+ # class Money
38
+ # include Comparable
39
+ # attr_reader :amount, :currency
40
+ # EXCHANGE_RATES = { "USD_TO_DKK" => 6 }
41
+ #
42
+ # def initialize(amount, currency = "USD")
43
+ # @amount, @currency = amount, currency
44
+ # end
45
+ #
46
+ # def exchange_to(other_currency)
47
+ # exchanged_amount = (amount * EXCHANGE_RATES["#{currency}_TO_#{other_currency}"]).floor
48
+ # Money.new(exchanged_amount, other_currency)
49
+ # end
50
+ #
51
+ # def ==(other_money)
52
+ # amount == other_money.amount && currency == other_money.currency
53
+ # end
54
+ #
55
+ # def <=>(other_money)
56
+ # if currency == other_money.currency
57
+ # amount <=> other_money.amount
58
+ # else
59
+ # amount <=> other_money.exchange_to(currency).amount
60
+ # end
61
+ # end
62
+ # end
63
+ #
64
+ # class Address
65
+ # attr_reader :street, :city
66
+ # def initialize(street, city)
67
+ # @street, @city = street, city
68
+ # end
69
+ #
70
+ # def close_to?(other_address)
71
+ # city == other_address.city
72
+ # end
73
+ #
74
+ # def ==(other_address)
75
+ # city == other_address.city && street == other_address.street
76
+ # end
77
+ # end
78
+ #
79
+ # Now it's possible to access attributes from the database through the value objects instead. If
80
+ # you choose to name the composition the same as the attribute's name, it will be the only way to
81
+ # access that attribute. That's the case with our +balance+ attribute. You interact with the value
82
+ # objects just like you would with any other attribute:
83
+ #
84
+ # customer.balance = Money.new(20) # sets the Money value object and the attribute
85
+ # customer.balance # => Money value object
86
+ # customer.balance.exchange_to("DKK") # => Money.new(120, "DKK")
87
+ # customer.balance > Money.new(10) # => true
88
+ # customer.balance == Money.new(20) # => true
89
+ # customer.balance < Money.new(5) # => false
90
+ #
91
+ # Value objects can also be composed of multiple attributes, such as the case of Address. The order
92
+ # of the mappings will determine the order of the parameters.
93
+ #
94
+ # customer.address_street = "Hyancintvej"
95
+ # customer.address_city = "Copenhagen"
96
+ # customer.address # => Address.new("Hyancintvej", "Copenhagen")
97
+ #
98
+ # customer.address = Address.new("May Street", "Chicago")
99
+ # customer.address_street # => "May Street"
100
+ # customer.address_city # => "Chicago"
101
+ #
102
+ # == Writing value objects
103
+ #
104
+ # Value objects are immutable and interchangeable objects that represent a given value, such as
105
+ # a Money object representing $5. Two Money objects both representing $5 should be equal (through
106
+ # methods such as <tt>==</tt> and <tt><=></tt> from Comparable if ranking makes sense). This is
107
+ # unlike entity objects where equality is determined by identity. An entity class such as Customer can
108
+ # easily have two different objects that both have an address on Hyancintvej. Entity identity is
109
+ # determined by object or relational unique identifiers (such as primary keys). Normal
110
+ # ActiveEntity::Base classes are entity objects.
111
+ #
112
+ # It's also important to treat the value objects as immutable. Don't allow the Money object to have
113
+ # its amount changed after creation. Create a new Money object with the new value instead. The
114
+ # <tt>Money#exchange_to</tt> method is an example of this. It returns a new value object instead of changing
115
+ # its own values. Active Entity won't persist value objects that have been changed through means
116
+ # other than the writer method.
117
+ #
118
+ # The immutable requirement is enforced by Active Entity by freezing any object assigned as a value
119
+ # object. Attempting to change it afterwards will result in a +RuntimeError+.
120
+ #
121
+ # Read more about value objects on http://c2.com/cgi/wiki?ValueObject and on the dangers of not
122
+ # keeping value objects immutable on http://c2.com/cgi/wiki?ValueObjectsShouldBeImmutable
123
+ #
124
+ # == Custom constructors and converters
125
+ #
126
+ # By default value objects are initialized by calling the <tt>new</tt> constructor of the value
127
+ # class passing each of the mapped attributes, in the order specified by the <tt>:mapping</tt>
128
+ # option, as arguments. If the value class doesn't support this convention then #composed_of allows
129
+ # a custom constructor to be specified.
130
+ #
131
+ # When a new value is assigned to the value object, the default assumption is that the new value
132
+ # is an instance of the value class. Specifying a custom converter allows the new value to be automatically
133
+ # converted to an instance of value class if necessary.
134
+ #
135
+ # For example, the +NetworkResource+ model has +network_address+ and +cidr_range+ attributes that should be
136
+ # aggregated using the +NetAddr::CIDR+ value class (https://www.rubydoc.info/gems/netaddr/1.5.0/NetAddr/CIDR).
137
+ # The constructor for the value class is called +create+ and it expects a CIDR address string as a parameter.
138
+ # New values can be assigned to the value object using either another +NetAddr::CIDR+ object, a string
139
+ # or an array. The <tt>:constructor</tt> and <tt>:converter</tt> options can be used to meet
140
+ # these requirements:
141
+ #
142
+ # class NetworkResource < ActiveEntity::Base
143
+ # composed_of :cidr,
144
+ # class_name: 'NetAddr::CIDR',
145
+ # mapping: [ %w(network_address network), %w(cidr_range bits) ],
146
+ # allow_nil: true,
147
+ # constructor: Proc.new { |network_address, cidr_range| NetAddr::CIDR.create("#{network_address}/#{cidr_range}") },
148
+ # converter: Proc.new { |value| NetAddr::CIDR.create(value.is_a?(Array) ? value.join('/') : value) }
149
+ # end
150
+ #
151
+ # # This calls the :constructor
152
+ # network_resource = NetworkResource.new(network_address: '192.168.0.1', cidr_range: 24)
153
+ #
154
+ # # These assignments will both use the :converter
155
+ # network_resource.cidr = [ '192.168.2.1', 8 ]
156
+ # network_resource.cidr = '192.168.0.1/24'
157
+ #
158
+ # # This assignment won't use the :converter as the value is already an instance of the value class
159
+ # network_resource.cidr = NetAddr::CIDR.create('192.168.2.1/8')
160
+ #
161
+ # # Saving and then reloading will use the :constructor on reload
162
+ # network_resource.save
163
+ # network_resource.reload
164
+ #
165
+ # == Finding records by a value object
166
+ #
167
+ # Once a #composed_of relationship is specified for a model, records can be loaded from the database
168
+ # by specifying an instance of the value object in the conditions hash. The following example
169
+ # finds all customers with +address_street+ equal to "May Street" and +address_city+ equal to "Chicago":
170
+ #
171
+ # Customer.where(address: Address.new("May Street", "Chicago"))
172
+ #
173
+ module ClassMethods
174
+ # Adds reader and writer methods for manipulating a value object:
175
+ # <tt>composed_of :address</tt> adds <tt>address</tt> and <tt>address=(new_address)</tt> methods.
176
+ #
177
+ # Options are:
178
+ # * <tt>:class_name</tt> - Specifies the class name of the association. Use it only if that name
179
+ # can't be inferred from the part id. So <tt>composed_of :address</tt> will by default be linked
180
+ # to the Address class, but if the real class name is +CompanyAddress+, you'll have to specify it
181
+ # with this option.
182
+ # * <tt>:mapping</tt> - Specifies the mapping of entity attributes to attributes of the value
183
+ # object. Each mapping is represented as an array where the first item is the name of the
184
+ # entity attribute and the second item is the name of the attribute in the value object. The
185
+ # order in which mappings are defined determines the order in which attributes are sent to the
186
+ # value class constructor.
187
+ # * <tt>:allow_nil</tt> - Specifies that the value object will not be instantiated when all mapped
188
+ # attributes are +nil+. Setting the value object to +nil+ has the effect of writing +nil+ to all
189
+ # mapped attributes.
190
+ # This defaults to +false+.
191
+ # * <tt>:constructor</tt> - A symbol specifying the name of the constructor method or a Proc that
192
+ # is called to initialize the value object. The constructor is passed all of the mapped attributes,
193
+ # in the order that they are defined in the <tt>:mapping option</tt>, as arguments and uses them
194
+ # to instantiate a <tt>:class_name</tt> object.
195
+ # The default is <tt>:new</tt>.
196
+ # * <tt>:converter</tt> - A symbol specifying the name of a class method of <tt>:class_name</tt>
197
+ # or a Proc that is called when a new value is assigned to the value object. The converter is
198
+ # passed the single value that is used in the assignment and is only called if the new value is
199
+ # not an instance of <tt>:class_name</tt>. If <tt>:allow_nil</tt> is set to true, the converter
200
+ # can return +nil+ to skip the assignment.
201
+ #
202
+ # Option examples:
203
+ # composed_of :temperature, mapping: %w(reading celsius)
204
+ # composed_of :balance, class_name: "Money", mapping: %w(balance amount)
205
+ # composed_of :address, mapping: [ %w(address_street street), %w(address_city city) ]
206
+ # composed_of :gps_location
207
+ # composed_of :gps_location, allow_nil: true
208
+ # composed_of :ip_address,
209
+ # class_name: 'IPAddr',
210
+ # mapping: %w(ip to_i),
211
+ # constructor: Proc.new { |ip| IPAddr.new(ip, Socket::AF_INET) },
212
+ # converter: Proc.new { |ip| ip.is_a?(Integer) ? IPAddr.new(ip, Socket::AF_INET) : IPAddr.new(ip.to_s) }
213
+ #
214
+ def composed_of(part_id, options = {})
215
+ options.assert_valid_keys(:class_name, :mapping, :allow_nil, :constructor, :converter)
216
+
217
+ unless self < Aggregations
218
+ include Aggregations
219
+ end
220
+
221
+ name = part_id.id2name
222
+ class_name = options[:class_name] || name.camelize
223
+ mapping = options[:mapping] || [ name, name ]
224
+ mapping = [ mapping ] unless mapping.first.is_a?(Array)
225
+ allow_nil = options[:allow_nil] || false
226
+ constructor = options[:constructor] || :new
227
+ converter = options[:converter]
228
+
229
+ reader_method(name, class_name, mapping, allow_nil, constructor)
230
+ writer_method(name, class_name, mapping, allow_nil, converter)
231
+
232
+ reflection = ActiveEntity::Reflection.create(:composed_of, part_id, nil, options, self)
233
+ Reflection.add_aggregate_reflection self, part_id, reflection
234
+ end
235
+
236
+ private
237
+
238
+ def reader_method(name, class_name, mapping, allow_nil, constructor)
239
+ define_method(name) do
240
+ if @aggregation_cache[name].nil? && (!allow_nil || mapping.any? { |key, _| !_read_attribute(key).nil? })
241
+ attrs = mapping.collect { |key, _| _read_attribute(key) }
242
+ object = constructor.respond_to?(:call) ?
243
+ constructor.call(*attrs) :
244
+ class_name.constantize.send(constructor, *attrs)
245
+ @aggregation_cache[name] = object
246
+ end
247
+ @aggregation_cache[name]
248
+ end
249
+ end
250
+
251
+ def writer_method(name, class_name, mapping, allow_nil, converter)
252
+ define_method("#{name}=") do |part|
253
+ klass = class_name.constantize
254
+
255
+ unless part.is_a?(klass) || converter.nil? || part.nil?
256
+ part = converter.respond_to?(:call) ? converter.call(part) : klass.send(converter, part)
257
+ end
258
+
259
+ hash_from_multiparameter_assignment = part.is_a?(Hash) &&
260
+ part.each_key.all? { |k| k.is_a?(Integer) }
261
+ if hash_from_multiparameter_assignment
262
+ raise ArgumentError unless part.size == part.each_key.max
263
+ part = klass.new(*part.sort.map(&:last))
264
+ end
265
+
266
+ if part.nil? && allow_nil
267
+ mapping.each { |key, _| self[key] = nil }
268
+ @aggregation_cache[name] = nil
269
+ else
270
+ mapping.each { |key, value| self[key] = part.send(value) }
271
+ @aggregation_cache[name] = part.freeze
272
+ end
273
+ end
274
+ end
275
+ end
276
+ end
277
+ end
@@ -0,0 +1,134 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/core_ext/array/wrap"
4
+
5
+ module ActiveEntity
6
+ module Associations
7
+ module Embeds
8
+ # = Active Entity Associations
9
+ #
10
+ # This is the root class of all associations ('+ Foo' signifies an included module Foo):
11
+ #
12
+ # Association
13
+ # SingularAssociation
14
+ # HasOneAssociation + ForeignAssociation
15
+ # HasOneThroughAssociation + ThroughAssociation
16
+ # BelongsToAssociation
17
+ # BelongsToPolymorphicAssociation
18
+ # CollectionAssociation
19
+ # HasManyAssociation + ForeignAssociation
20
+ # HasManyThroughAssociation + ThroughAssociation
21
+ class Association #:nodoc:
22
+ attr_reader :owner, :target, :reflection
23
+
24
+ delegate :options, to: :reflection
25
+
26
+ def initialize(owner, reflection)
27
+ reflection.check_validity!
28
+
29
+ @owner, @reflection = owner, reflection
30
+
31
+ @target = nil
32
+ @inversed = false
33
+ end
34
+
35
+ # Has the \target been already \loaded?
36
+ def loaded?
37
+ true
38
+ end
39
+
40
+ # Sets the target of this association to <tt>\target</tt>, and the \loaded flag to +true+.
41
+ attr_writer :target
42
+
43
+ # Set the inverse association, if possible
44
+ def set_inverse_instance(record)
45
+ if inverse = inverse_association_for(record)
46
+ inverse.inversed_from(owner)
47
+ end
48
+ record
49
+ end
50
+
51
+ # Remove the inverse association, if possible
52
+ def remove_inverse_instance(record)
53
+ if inverse = inverse_association_for(record)
54
+ inverse.inversed_from(nil)
55
+ end
56
+ end
57
+
58
+ def inversed_from(record)
59
+ self.target = record
60
+ @inversed = !!record
61
+ end
62
+
63
+ # Returns the class of the target. belongs_to polymorphic overrides this to look at the
64
+ # polymorphic_type field on the owner.
65
+ def klass
66
+ reflection.klass
67
+ end
68
+
69
+ def extensions
70
+ reflection.extensions
71
+ end
72
+
73
+ # We can't dump @reflection and @through_reflection since it contains the scope proc
74
+ def marshal_dump
75
+ ivars = (instance_variables - [:@reflection, :@through_reflection]).map { |name| [name, instance_variable_get(name)] }
76
+ [@reflection.name, ivars]
77
+ end
78
+
79
+ def marshal_load(data)
80
+ reflection_name, ivars = data
81
+ ivars.each { |name, val| instance_variable_set(name, val) }
82
+ @reflection = @owner.class._reflect_on_association(reflection_name)
83
+ end
84
+
85
+ def initialize_attributes(record, attributes = {}) #:nodoc:
86
+ record.assign_attributes attributes if attributes.any?
87
+ set_inverse_instance(record)
88
+ end
89
+
90
+ private
91
+
92
+ # Raises ActiveEntity::AssociationTypeMismatch unless +record+ is of
93
+ # the kind of the class of the associated objects. Meant to be used as
94
+ # a sanity check when you are about to assign an associated record.
95
+ def raise_on_type_mismatch!(record)
96
+ unless record.is_a?(reflection.klass)
97
+ fresh_class = reflection.class_name.safe_constantize
98
+ unless fresh_class && record.is_a?(fresh_class)
99
+ message = "#{reflection.class_name}(##{reflection.klass.object_id}) expected, "\
100
+ "got #{record.inspect} which is an instance of #{record.class}(##{record.class.object_id})"
101
+ raise ActiveEntity::AssociationTypeMismatch, message
102
+ end
103
+ end
104
+ end
105
+
106
+ def inverse_association_for(record)
107
+ if invertible_for?(record)
108
+ record.association(inverse_reflection_for(record).name)
109
+ end
110
+ end
111
+
112
+ # Can be redefined by subclasses, notably polymorphic belongs_to
113
+ # The record parameter is necessary to support polymorphic inverses as we must check for
114
+ # the association in the specific class of the record.
115
+ def inverse_reflection_for(record)
116
+ reflection.inverse_of
117
+ end
118
+
119
+ # Returns true if inverse association on the given record needs to be set.
120
+ # This method is redefined by subclasses.
121
+ def invertible_for?(record)
122
+ inverse_reflection_for(record)
123
+ end
124
+
125
+ def build_record(attributes)
126
+ reflection.build_association(attributes) do |record|
127
+ initialize_attributes(record, attributes)
128
+ yield(record) if block_given?
129
+ end
130
+ end
131
+ end
132
+ end
133
+ end
134
+ end
@@ -0,0 +1,105 @@
1
+ # frozen_string_literal: true
2
+
3
+ # This is the parent Association class which defines the variables
4
+ # used by all associations.
5
+ #
6
+ # The hierarchy is defined as follows:
7
+ # Association
8
+ # - SingularAssociation
9
+ # - BelongsToAssociation
10
+ # - HasOneAssociation
11
+ # - CollectionAssociation
12
+ # - HasManyAssociation
13
+
14
+ module ActiveEntity::Associations::Embeds::Builder # :nodoc:
15
+ class Association #:nodoc:
16
+ class << self
17
+ attr_accessor :extensions
18
+ end
19
+ self.extensions = []
20
+
21
+ VALID_OPTIONS = [:class_name, :anonymous_class, :validate] # :nodoc:
22
+
23
+ def self.build(model, name, options)
24
+ if model.dangerous_attribute_method?(name)
25
+ raise ArgumentError, "You tried to define an association named #{name} on the model #{model.name}, but " \
26
+ "this will conflict with a method #{name} already defined by Active Entity. " \
27
+ "Please choose a different association name."
28
+ end
29
+
30
+ reflection = create_reflection model, name, options
31
+ define_accessors model, reflection
32
+ define_callbacks model, reflection
33
+ define_validations model, reflection
34
+ reflection
35
+ end
36
+
37
+ def self.create_reflection(model, name, options, &block)
38
+ raise ArgumentError, "association names must be a Symbol" unless name.kind_of?(Symbol)
39
+
40
+ validate_options(options)
41
+
42
+ extension = define_extensions(model, name, &block)
43
+ options[:extend] = [*options[:extend], extension] if extension
44
+
45
+ ActiveEntity::Reflection.create(macro, name, nil, options, model)
46
+ end
47
+
48
+ def self.macro
49
+ raise NotImplementedError
50
+ end
51
+
52
+ def self.valid_options(options)
53
+ VALID_OPTIONS + Association.extensions.flat_map(&:valid_options)
54
+ end
55
+
56
+ def self.validate_options(options)
57
+ options.assert_valid_keys(valid_options(options))
58
+ end
59
+
60
+ def self.define_extensions(model, name)
61
+ end
62
+
63
+ def self.define_callbacks(model, reflection)
64
+ Association.extensions.each do |extension|
65
+ extension.build model, reflection
66
+ end
67
+ end
68
+
69
+ # Defines the setter and getter methods for the association
70
+ # class Post < ActiveEntity::Base
71
+ # has_many :comments
72
+ # end
73
+ #
74
+ # Post.first.comments and Post.first.comments= methods are defined by this method...
75
+ def self.define_accessors(model, reflection)
76
+ mixin = model.generated_association_methods
77
+ name = reflection.name
78
+ define_readers(mixin, name)
79
+ define_writers(mixin, name)
80
+ end
81
+
82
+ def self.define_readers(mixin, name)
83
+ mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
84
+ def #{name}
85
+ association(:#{name}).reader
86
+ end
87
+ CODE
88
+ end
89
+
90
+ def self.define_writers(mixin, name)
91
+ mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
92
+ def #{name}=(value)
93
+ association(:#{name}).writer(value)
94
+ end
95
+ CODE
96
+ end
97
+
98
+ def self.define_validations(_model, _reflection)
99
+ # noop
100
+ end
101
+
102
+ private_class_method :macro, :valid_options, :validate_options, :define_extensions,
103
+ :define_callbacks, :define_accessors, :define_readers, :define_writers, :define_validations
104
+ end
105
+ end