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,240 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_model/attribute/user_provided_default"
4
+
5
+ module ActiveEntity
6
+ # See ActiveEntity::Attributes::ClassMethods for documentation
7
+ module Attributes
8
+ extend ActiveSupport::Concern
9
+
10
+ included do
11
+ class_attribute :attributes_to_define_after_schema_loads, instance_accessor: false, default: {} # :internal:
12
+ end
13
+
14
+ module ClassMethods
15
+ # Defines an attribute with a type on this model. It will override the
16
+ # type of existing attributes if needed. This allows control over how
17
+ # values are converted to and from SQL when assigned to a model. It also
18
+ # changes the behavior of values passed to
19
+ # {ActiveEntity::Base.where}[rdoc-ref:QueryMethods#where]. This will let you use
20
+ # your domain objects across much of Active Entity, without having to
21
+ # rely on implementation details or monkey patching.
22
+ #
23
+ # +name+ The name of the methods to define attribute methods for, and the
24
+ # column which this will persist to.
25
+ #
26
+ # +cast_type+ A symbol such as +:string+ or +:integer+, or a type object
27
+ # to be used for this attribute. See the examples below for more
28
+ # information about providing custom type objects.
29
+ #
30
+ # ==== Options
31
+ #
32
+ # The following options are accepted:
33
+ #
34
+ # +default+ The default value to use when no value is provided. If this option
35
+ # is not passed, the previous default value (if any) will be used.
36
+ # Otherwise, the default will be +nil+.
37
+ #
38
+ # +array+ (PostgreSQL only) specifies that the type should be an array (see the
39
+ # examples below).
40
+ #
41
+ # +range+ (PostgreSQL only) specifies that the type should be a range (see the
42
+ # examples below).
43
+ #
44
+ # When using a symbol for +cast_type+, extra options are forwarded to the
45
+ # constructor of the type object.
46
+ #
47
+ # ==== Examples
48
+ #
49
+ # The type detected by Active Entity can be overridden.
50
+ #
51
+ # # db/schema.rb
52
+ # create_table :store_listings, force: true do |t|
53
+ # t.decimal :price_in_cents
54
+ # end
55
+ #
56
+ # # app/models/store_listing.rb
57
+ # class StoreListing < ActiveEntity::Base
58
+ # end
59
+ #
60
+ # store_listing = StoreListing.new(price_in_cents: '10.1')
61
+ #
62
+ # # before
63
+ # store_listing.price_in_cents # => BigDecimal(10.1)
64
+ #
65
+ # class StoreListing < ActiveEntity::Base
66
+ # attribute :price_in_cents, :integer
67
+ # end
68
+ #
69
+ # # after
70
+ # store_listing.price_in_cents # => 10
71
+ #
72
+ # A default can also be provided.
73
+ #
74
+ # # db/schema.rb
75
+ # create_table :store_listings, force: true do |t|
76
+ # t.string :my_string, default: "original default"
77
+ # end
78
+ #
79
+ # StoreListing.new.my_string # => "original default"
80
+ #
81
+ # # app/models/store_listing.rb
82
+ # class StoreListing < ActiveEntity::Base
83
+ # attribute :my_string, :string, default: "new default"
84
+ # end
85
+ #
86
+ # StoreListing.new.my_string # => "new default"
87
+ #
88
+ # class Product < ActiveEntity::Base
89
+ # attribute :my_default_proc, :datetime, default: -> { Time.now }
90
+ # end
91
+ #
92
+ # Product.new.my_default_proc # => 2015-05-30 11:04:48 -0600
93
+ # sleep 1
94
+ # Product.new.my_default_proc # => 2015-05-30 11:04:49 -0600
95
+ #
96
+ # \Attributes do not need to be backed by a database column.
97
+ #
98
+ # # app/models/my_model.rb
99
+ # class MyModel < ActiveEntity::Base
100
+ # attribute :my_string, :string
101
+ # attribute :my_int_array, :integer, array: true
102
+ # attribute :my_float_range, :float, range: true
103
+ # end
104
+ #
105
+ # model = MyModel.new(
106
+ # my_string: "string",
107
+ # my_int_array: ["1", "2", "3"],
108
+ # my_float_range: "[1,3.5]",
109
+ # )
110
+ # model.attributes
111
+ # # =>
112
+ # {
113
+ # my_string: "string",
114
+ # my_int_array: [1, 2, 3],
115
+ # my_float_range: 1.0..3.5
116
+ # }
117
+ #
118
+ # Passing options to the type constructor
119
+ #
120
+ # # app/models/my_model.rb
121
+ # class MyModel < ActiveEntity::Base
122
+ # attribute :small_int, :integer, limit: 2
123
+ # end
124
+ #
125
+ # MyModel.create(small_int: 65537)
126
+ # # => Error: 65537 is out of range for the limit of two bytes
127
+ #
128
+ # ==== Creating Custom Types
129
+ #
130
+ # Users may also define their own custom types, as long as they respond
131
+ # to the methods defined on the value type. The method +deserialize+ or
132
+ # +cast+ will be called on your type object, with raw input from the
133
+ # database or from your controllers. See ActiveModel::Type::Value for the
134
+ # expected API. It is recommended that your type objects inherit from an
135
+ # existing type, or from ActiveEntity::Type::Value
136
+ #
137
+ # class MoneyType < ActiveEntity::Type::Integer
138
+ # def cast(value)
139
+ # if !value.kind_of?(Numeric) && value.include?('$')
140
+ # price_in_dollars = value.gsub(/\$/, '').to_f
141
+ # super(price_in_dollars * 100)
142
+ # else
143
+ # super
144
+ # end
145
+ # end
146
+ # end
147
+ #
148
+ # # config/initializers/types.rb
149
+ # ActiveEntity::Type.register(:money, MoneyType)
150
+ #
151
+ # # app/models/store_listing.rb
152
+ # class StoreListing < ActiveEntity::Base
153
+ # attribute :price_in_cents, :money
154
+ # end
155
+ #
156
+ # store_listing = StoreListing.new(price_in_cents: '$10.00')
157
+ # store_listing.price_in_cents # => 1000
158
+ #
159
+ # For more details on creating custom types, see the documentation for
160
+ # ActiveModel::Type::Value. For more details on registering your types
161
+ # to be referenced by a symbol, see ActiveEntity::Type.register. You can
162
+ # also pass a type object directly, in place of a symbol.
163
+ #
164
+ # ==== Dirty Tracking
165
+ #
166
+ # The type of an attribute is given the opportunity to change how dirty
167
+ # tracking is performed. The methods +changed?+ and +changed_in_place?+
168
+ # will be called from ActiveModel::Dirty. See the documentation for those
169
+ # methods in ActiveModel::Type::Value for more details.
170
+ def attribute(name, cast_type = Type::Value.new, **options)
171
+ name = name.to_s
172
+ reload_schema_from_cache
173
+
174
+ self.attributes_to_define_after_schema_loads =
175
+ attributes_to_define_after_schema_loads.merge(
176
+ name => [cast_type, options]
177
+ )
178
+ end
179
+
180
+ # This is the low level API which sits beneath +attribute+. It only
181
+ # accepts type objects, and will do its work immediately instead of
182
+ # waiting for the schema to load. Automatic schema detection and
183
+ # ClassMethods#attribute both call this under the hood. While this method
184
+ # is provided so it can be used by plugin authors, application code
185
+ # should probably use ClassMethods#attribute.
186
+ #
187
+ # +name+ The name of the attribute being defined. Expected to be a +String+.
188
+ #
189
+ # +cast_type+ The type object to use for this attribute.
190
+ #
191
+ # +default+ The default value to use when no value is provided. If this option
192
+ # is not passed, the previous default value (if any) will be used.
193
+ # Otherwise, the default will be +nil+. A proc can also be passed, and
194
+ # will be called once each time a new value is needed.
195
+ #
196
+ # +cast+ or +deserialize+.
197
+ def define_attribute(
198
+ name,
199
+ cast_type,
200
+ default: NO_DEFAULT_PROVIDED
201
+ )
202
+ attribute_types[name] = cast_type
203
+ define_default_attribute(name, default, cast_type)
204
+ define_attribute_method(name)
205
+ end
206
+
207
+ def load_schema! # :nodoc:
208
+ super
209
+ attributes_to_define_after_schema_loads.each do |name, (type, options)|
210
+ if type.is_a?(Symbol)
211
+ type = ActiveEntity::Type.lookup(type, **options.except(:default))
212
+ end
213
+
214
+ define_attribute(name, type, **options.slice(:default))
215
+ end
216
+ end
217
+
218
+ private
219
+
220
+ NO_DEFAULT_PROVIDED = Object.new # :nodoc:
221
+ private_constant :NO_DEFAULT_PROVIDED
222
+
223
+ def define_default_attribute(name, value, type)
224
+ default_attribute =
225
+ if value == NO_DEFAULT_PROVIDED
226
+ _default_attributes[name].with_type(type)
227
+ else
228
+ ActiveModel::Attribute::UserProvidedDefault.new(
229
+ name,
230
+ value,
231
+ type,
232
+ _default_attributes.fetch(name.to_s) { nil },
233
+ )
234
+ end
235
+
236
+ _default_attributes[name] = default_attribute
237
+ end
238
+ end
239
+ end
240
+ end
@@ -0,0 +1,293 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/benchmarkable"
4
+ require "active_support/dependencies"
5
+ require "active_support/descendants_tracker"
6
+ require "active_support/time"
7
+ require "active_support/core_ext/class/subclasses"
8
+ require "active_entity/attribute_decorators"
9
+ require "active_entity/attributes"
10
+
11
+ module ActiveEntity #:nodoc:
12
+ # = Active Entity
13
+ #
14
+ # Active Entity objects don't specify their attributes directly, but rather infer them from
15
+ # the table definition with which they're linked. Adding, removing, and changing attributes
16
+ # and their type is done directly in the database. Any change is instantly reflected in the
17
+ # Active Entity objects. The mapping that binds a given Active Entity class to a certain
18
+ # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
19
+ #
20
+ # See the mapping rules in table_name and the full example in link:files/activeentity/README_rdoc.html for more insight.
21
+ #
22
+ # == Creation
23
+ #
24
+ # Active Entitys accept constructor parameters either in a hash or as a block. The hash
25
+ # method is especially useful when you're receiving the data from somewhere else, like an
26
+ # HTTP request. It works like this:
27
+ #
28
+ # user = User.new(name: "David", occupation: "Code Artist")
29
+ # user.name # => "David"
30
+ #
31
+ # You can also use block initialization:
32
+ #
33
+ # user = User.new do |u|
34
+ # u.name = "David"
35
+ # u.occupation = "Code Artist"
36
+ # end
37
+ #
38
+ # And of course you can just create a bare object and specify the attributes after the fact:
39
+ #
40
+ # user = User.new
41
+ # user.name = "David"
42
+ # user.occupation = "Code Artist"
43
+ #
44
+ # == Conditions
45
+ #
46
+ # Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement.
47
+ # The array form is to be used when the condition input is tainted and requires sanitization. The string form can
48
+ # be used for statements that don't involve tainted data. The hash form works much like the array form, except
49
+ # only equality and range is possible. Examples:
50
+ #
51
+ # class User < ActiveEntity::Base
52
+ # def self.authenticate_unsafely(user_name, password)
53
+ # where("user_name = '#{user_name}' AND password = '#{password}'").first
54
+ # end
55
+ #
56
+ # def self.authenticate_safely(user_name, password)
57
+ # where("user_name = ? AND password = ?", user_name, password).first
58
+ # end
59
+ #
60
+ # def self.authenticate_safely_simply(user_name, password)
61
+ # where(user_name: user_name, password: password).first
62
+ # end
63
+ # end
64
+ #
65
+ # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query
66
+ # and is thus susceptible to SQL-injection attacks if the <tt>user_name</tt> and +password+
67
+ # parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and
68
+ # <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+
69
+ # before inserting them in the query, which will ensure that an attacker can't escape the
70
+ # query and fake the login (or worse).
71
+ #
72
+ # When using multiple parameters in the conditions, it can easily become hard to read exactly
73
+ # what the fourth or fifth question mark is supposed to represent. In those cases, you can
74
+ # resort to named bind variables instead. That's done by replacing the question marks with
75
+ # symbols and supplying a hash with values for the matching symbol keys:
76
+ #
77
+ # Company.where(
78
+ # "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
79
+ # { id: 3, name: "37signals", division: "First", accounting_date: '2005-01-01' }
80
+ # ).first
81
+ #
82
+ # Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
83
+ # operator. For instance:
84
+ #
85
+ # Student.where(first_name: "Harvey", status: 1)
86
+ # Student.where(params[:student])
87
+ #
88
+ # A range may be used in the hash to use the SQL BETWEEN operator:
89
+ #
90
+ # Student.where(grade: 9..12)
91
+ #
92
+ # An array may be used in the hash to use the SQL IN operator:
93
+ #
94
+ # Student.where(grade: [9,11,12])
95
+ #
96
+ # When joining tables, nested hashes or keys written in the form 'table_name.column_name'
97
+ # can be used to qualify the table name of a particular condition. For instance:
98
+ #
99
+ # Student.joins(:schools).where(schools: { category: 'public' })
100
+ # Student.joins(:schools).where('schools.category' => 'public' )
101
+ #
102
+ # == Overwriting default accessors
103
+ #
104
+ # All column values are automatically available through basic accessors on the Active Entity
105
+ # object, but sometimes you want to specialize this behavior. This can be done by overwriting
106
+ # the default accessors (using the same name as the attribute) and calling
107
+ # +super+ to actually change things.
108
+ #
109
+ # class Song < ActiveEntity::Base
110
+ # # Uses an integer of seconds to hold the length of the song
111
+ #
112
+ # def length=(minutes)
113
+ # super(minutes.to_i * 60)
114
+ # end
115
+ #
116
+ # def length
117
+ # super / 60
118
+ # end
119
+ # end
120
+ #
121
+ # == Attribute query methods
122
+ #
123
+ # In addition to the basic accessors, query methods are also automatically available on the Active Entity object.
124
+ # Query methods allow you to test whether an attribute value is present.
125
+ # Additionally, when dealing with numeric values, a query method will return false if the value is zero.
126
+ #
127
+ # For example, an Active Entity User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call
128
+ # to determine whether the user has a name:
129
+ #
130
+ # user = User.new(name: "David")
131
+ # user.name? # => true
132
+ #
133
+ # anonymous = User.new(name: "")
134
+ # anonymous.name? # => false
135
+ #
136
+ # == Accessing attributes before they have been typecasted
137
+ #
138
+ # Sometimes you want to be able to read the raw attribute data without having the column-determined
139
+ # typecast run its course first. That can be done by using the <tt><attribute>_before_type_cast</tt>
140
+ # accessors that all attributes have. For example, if your Account model has a <tt>balance</tt> attribute,
141
+ # you can call <tt>account.balance_before_type_cast</tt> or <tt>account.id_before_type_cast</tt>.
142
+ #
143
+ # This is especially useful in validation situations where the user might supply a string for an
144
+ # integer field and you want to display the original string back in an error message. Accessing the
145
+ # attribute normally would typecast the string to 0, which isn't what you want.
146
+ #
147
+ # == Dynamic attribute-based finders
148
+ #
149
+ # Dynamic attribute-based finders are a mildly deprecated way of getting (and/or creating) objects
150
+ # by simple queries without turning to SQL. They work by appending the name of an attribute
151
+ # to <tt>find_by_</tt> like <tt>Person.find_by_user_name</tt>.
152
+ # Instead of writing <tt>Person.find_by(user_name: user_name)</tt>, you can use
153
+ # <tt>Person.find_by_user_name(user_name)</tt>.
154
+ #
155
+ # It's possible to add an exclamation point (!) on the end of the dynamic finders to get them to raise an
156
+ # ActiveEntity::RecordNotFound error if they do not return any records,
157
+ # like <tt>Person.find_by_last_name!</tt>.
158
+ #
159
+ # It's also possible to use multiple attributes in the same <tt>find_by_</tt> by separating them with
160
+ # "_and_".
161
+ #
162
+ # Person.find_by(user_name: user_name, password: password)
163
+ # Person.find_by_user_name_and_password(user_name, password) # with dynamic finder
164
+ #
165
+ # It's even possible to call these dynamic finder methods on relations and named scopes.
166
+ #
167
+ # Payment.order("created_on").find_by_amount(50)
168
+ #
169
+ # == Saving arrays, hashes, and other non-mappable objects in text columns
170
+ #
171
+ # Active Entity can serialize any object in text columns using YAML. To do so, you must
172
+ # specify this with a call to the class method
173
+ # {serialize}[rdoc-ref:AttributeMethods::Serialization::ClassMethods#serialize].
174
+ # This makes it possible to store arrays, hashes, and other non-mappable objects without doing
175
+ # any additional work.
176
+ #
177
+ # class User < ActiveEntity::Base
178
+ # serialize :preferences
179
+ # end
180
+ #
181
+ # user = User.create(preferences: { "background" => "black", "display" => large })
182
+ # User.find(user.id).preferences # => { "background" => "black", "display" => large }
183
+ #
184
+ # You can also specify a class option as the second parameter that'll raise an exception
185
+ # if a serialized object is retrieved as a descendant of a class not in the hierarchy.
186
+ #
187
+ # class User < ActiveEntity::Base
188
+ # serialize :preferences, Hash
189
+ # end
190
+ #
191
+ # user = User.create(preferences: %w( one two three ))
192
+ # User.find(user.id).preferences # raises SerializationTypeMismatch
193
+ #
194
+ # When you specify a class option, the default value for that attribute will be a new
195
+ # instance of that class.
196
+ #
197
+ # class User < ActiveEntity::Base
198
+ # serialize :preferences, OpenStruct
199
+ # end
200
+ #
201
+ # user = User.new
202
+ # user.preferences.theme_color = "red"
203
+ #
204
+ #
205
+ # == Single table inheritance
206
+ #
207
+ # Active Entity allows inheritance by storing the name of the class in a
208
+ # column that is named "type" by default. See ActiveEntity::Inheritance for
209
+ # more details.
210
+ #
211
+ # == Connection to multiple databases in different models
212
+ #
213
+ # Connections are usually created through
214
+ # {ActiveEntity::Base.establish_connection}[rdoc-ref:ConnectionHandling#establish_connection] and retrieved
215
+ # by ActiveEntity::Base.connection. All classes inheriting from ActiveEntity::Base will use this
216
+ # connection. But you can also set a class-specific connection. For example, if Course is an
217
+ # ActiveEntity::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
218
+ # and Course and all of its subclasses will use this connection instead.
219
+ #
220
+ # This feature is implemented by keeping a connection pool in ActiveEntity::Base that is
221
+ # a hash indexed by the class. If a connection is requested, the
222
+ # {ActiveEntity::Base.retrieve_connection}[rdoc-ref:ConnectionHandling#retrieve_connection] method
223
+ # will go up the class-hierarchy until a connection is found in the connection pool.
224
+ #
225
+ # == Exceptions
226
+ #
227
+ # * ActiveEntityError - Generic error class and superclass of all other errors raised by Active Entity.
228
+ # * AdapterNotSpecified - The configuration hash used in
229
+ # {ActiveEntity::Base.establish_connection}[rdoc-ref:ConnectionHandling#establish_connection]
230
+ # didn't include an <tt>:adapter</tt> key.
231
+ # * AdapterNotFound - The <tt>:adapter</tt> key used in
232
+ # {ActiveEntity::Base.establish_connection}[rdoc-ref:ConnectionHandling#establish_connection]
233
+ # specified a non-existent adapter
234
+ # (or a bad spelling of an existing one).
235
+ # * AssociationTypeMismatch - The object assigned to the association wasn't of the type
236
+ # specified in the association definition.
237
+ # * AttributeAssignmentError - An error occurred while doing a mass assignment through the
238
+ # {ActiveEntity::Base#attributes=}[rdoc-ref:AttributeAssignment#attributes=] method.
239
+ # You can inspect the +attribute+ property of the exception object to determine which attribute
240
+ # triggered the error.
241
+ # * ConnectionNotEstablished - No connection has been established.
242
+ # Use {ActiveEntity::Base.establish_connection}[rdoc-ref:ConnectionHandling#establish_connection] before querying.
243
+ # * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the
244
+ # {ActiveEntity::Base#attributes=}[rdoc-ref:AttributeAssignment#attributes=] method.
245
+ # The +errors+ property of this exception contains an array of
246
+ # AttributeAssignmentError
247
+ # objects that should be inspected to determine which attributes triggered the errors.
248
+ # * RecordInvalid - raised by {ActiveEntity::Base#save!}[rdoc-ref:Persistence#save!] and
249
+ # {ActiveEntity::Base.create!}[rdoc-ref:Persistence::ClassMethods#create!]
250
+ # when the record is invalid.
251
+ # * RecordNotFound - No record responded to the {ActiveEntity::Base.find}[rdoc-ref:FinderMethods#find] method.
252
+ # Either the row with the given ID doesn't exist or the row didn't meet the additional restrictions.
253
+ # Some {ActiveEntity::Base.find}[rdoc-ref:FinderMethods#find] calls do not raise this exception to signal
254
+ # nothing was found, please check its documentation for further details.
255
+ # * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
256
+ # * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
257
+ #
258
+ # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
259
+ # So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all
260
+ # instances in the current object space.
261
+ class Base
262
+ extend ActiveModel::Naming
263
+
264
+ extend ActiveSupport::Benchmarkable
265
+ extend ActiveSupport::DescendantsTracker
266
+
267
+ extend Translation
268
+ extend Enum
269
+ extend Aggregations::ClassMethods
270
+
271
+ include Core
272
+ include Persistence
273
+ include ReadonlyAttributes
274
+ include ModelSchema
275
+ include Inheritance
276
+ include AttributeAssignment
277
+ include ActiveModel::Conversion
278
+ include Integration
279
+ include Validations
280
+ include Attributes
281
+ include AttributeDecorators
282
+ include AttributeMethods
283
+ include Callbacks
284
+ include Associations
285
+ include ValidateEmbedsAssociation
286
+ include NestedAttributes
287
+ include Reflection
288
+ include Serialization
289
+ include Store
290
+ end
291
+
292
+ ActiveSupport.run_load_hooks(:active_entity, Base)
293
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveEntity
4
+ module Callbacks
5
+ extend ActiveSupport::Concern
6
+
7
+ CALLBACKS = [
8
+ :after_initialize, :before_validation, :after_validation
9
+ ]
10
+
11
+ module ClassMethods # :nodoc:
12
+ include ActiveModel::Callbacks
13
+ end
14
+
15
+ included do
16
+ include ActiveModel::Validations::Callbacks
17
+
18
+ define_model_callbacks :initialize, only: :after
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveEntity
4
+ module Coders # :nodoc:
5
+ class JSON # :nodoc:
6
+ def self.dump(obj)
7
+ ActiveSupport::JSON.encode(obj)
8
+ end
9
+
10
+ def self.load(json)
11
+ ActiveSupport::JSON.decode(json) unless json.blank?
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+
5
+ module ActiveEntity
6
+ module Coders # :nodoc:
7
+ class YAMLColumn # :nodoc:
8
+ attr_accessor :object_class
9
+
10
+ def initialize(attr_name, object_class = Object)
11
+ @attr_name = attr_name
12
+ @object_class = object_class
13
+ check_arity_of_constructor
14
+ end
15
+
16
+ def dump(obj)
17
+ return if obj.nil?
18
+
19
+ assert_valid_value(obj, action: "dump")
20
+ YAML.dump obj
21
+ end
22
+
23
+ def load(yaml)
24
+ return object_class.new if object_class != Object && yaml.nil?
25
+ return yaml unless yaml.is_a?(String) && /^---/.match?(yaml)
26
+ obj = YAML.load(yaml)
27
+
28
+ assert_valid_value(obj, action: "load")
29
+ obj ||= object_class.new if object_class != Object
30
+
31
+ obj
32
+ end
33
+
34
+ def assert_valid_value(obj, action:)
35
+ unless obj.nil? || obj.is_a?(object_class)
36
+ raise SerializationTypeMismatch,
37
+ "can't #{action} `#{@attr_name}`: was supposed to be a #{object_class}, but was a #{obj.class}. -- #{obj.inspect}"
38
+ end
39
+ end
40
+
41
+ private
42
+
43
+ def check_arity_of_constructor
44
+ load(nil)
45
+ rescue ArgumentError
46
+ raise ArgumentError, "Cannot serialize #{object_class}. Classes passed to `serialize` must have a 0 argument constructor."
47
+ end
48
+ end
49
+ end
50
+ end