active_fields 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (56) hide show
  1. checksums.yaml +7 -0
  2. data/.rspec +2 -0
  3. data/.rubocop.yml +60 -0
  4. data/CHANGELOG.md +5 -0
  5. data/CODE_OF_CONDUCT.md +84 -0
  6. data/LICENSE +21 -0
  7. data/README.md +5 -0
  8. data/Rakefile +3 -0
  9. data/lib/active_fields/casters/base_caster.rb +18 -0
  10. data/lib/active_fields/casters/boolean_caster.rb +23 -0
  11. data/lib/active_fields/casters/date_array_caster.rb +21 -0
  12. data/lib/active_fields/casters/date_caster.rb +25 -0
  13. data/lib/active_fields/casters/decimal_array_caster.rb +21 -0
  14. data/lib/active_fields/casters/decimal_caster.rb +23 -0
  15. data/lib/active_fields/casters/enum_array_caster.rb +9 -0
  16. data/lib/active_fields/casters/enum_caster.rb +9 -0
  17. data/lib/active_fields/casters/integer_array_caster.rb +21 -0
  18. data/lib/active_fields/casters/integer_caster.rb +23 -0
  19. data/lib/active_fields/casters/text_array_caster.rb +21 -0
  20. data/lib/active_fields/casters/text_caster.rb +23 -0
  21. data/lib/active_fields/models/concerns/concern.rb +16 -0
  22. data/lib/active_fields/models/concerns/customizable.rb +83 -0
  23. data/lib/active_fields/models/concerns/field_concern.rb +79 -0
  24. data/lib/active_fields/models/concerns/value_concern.rb +50 -0
  25. data/lib/active_fields/models/field/boolean.rb +38 -0
  26. data/lib/active_fields/models/field/date.rb +48 -0
  27. data/lib/active_fields/models/field/date_array.rb +44 -0
  28. data/lib/active_fields/models/field/decimal.rb +48 -0
  29. data/lib/active_fields/models/field/decimal_array.rb +44 -0
  30. data/lib/active_fields/models/field/enum.rb +62 -0
  31. data/lib/active_fields/models/field/enum_array.rb +59 -0
  32. data/lib/active_fields/models/field/integer.rb +48 -0
  33. data/lib/active_fields/models/field/integer_array.rb +34 -0
  34. data/lib/active_fields/models/field/text.rb +49 -0
  35. data/lib/active_fields/models/field/text_array.rb +35 -0
  36. data/lib/active_fields/models/field.rb +27 -0
  37. data/lib/active_fields/models/value.rb +30 -0
  38. data/lib/active_fields/validators/base_validator.rb +73 -0
  39. data/lib/active_fields/validators/boolean_validator.rb +23 -0
  40. data/lib/active_fields/validators/date_array_validator.rb +28 -0
  41. data/lib/active_fields/validators/date_validator.rb +21 -0
  42. data/lib/active_fields/validators/decimal_array_validator.rb +28 -0
  43. data/lib/active_fields/validators/decimal_validator.rb +21 -0
  44. data/lib/active_fields/validators/enum_array_validator.rb +36 -0
  45. data/lib/active_fields/validators/enum_validator.rb +25 -0
  46. data/lib/active_fields/validators/integer_array_validator.rb +28 -0
  47. data/lib/active_fields/validators/integer_validator.rb +21 -0
  48. data/lib/active_fields/validators/text_array_validator.rb +28 -0
  49. data/lib/active_fields/validators/text_validator.rb +21 -0
  50. data/lib/active_fields/version.rb +5 -0
  51. data/lib/active_fields.rb +13 -0
  52. data/lib/generators/active_fields/install/USAGE +5 -0
  53. data/lib/generators/active_fields/install/install_generator.rb +33 -0
  54. data/lib/generators/active_fields/install/templates/create_active_fields_tables.rb.tt +30 -0
  55. data/sig/active_fields.rbs +4 -0
  56. metadata +282 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 81a03041febfec92f7fdbbb6e9f8b9e1f40cc715744467541fbb0c08011f5a22
4
+ data.tar.gz: f6d64ed4e8e703c66e0dd7deff7f41c1c8da60b35ff084b1ca8c20986b8776b5
5
+ SHA512:
6
+ metadata.gz: 660528c8044ef3000116b892cc236de565fe5530f9958b4a0f4ae9c511d2a3c3f4d8944fe6b2894d59f16b6bff6cd529acb6a592100c9e3cc396c0030d2069c6
7
+ data.tar.gz: 4843897cd9783e5d5489e0cf8c91d103d3136e23ee754ae447b77705f073e7e35750098a83e713ed77948d164d308eb8a690c206d0d52406c26eba0913817710
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,60 @@
1
+ require:
2
+ - rubocop-performance
3
+ - rubocop-rails
4
+ - rubocop-rake
5
+ - rubocop-rspec
6
+ - rubocop-factory_bot
7
+
8
+ inherit_gem:
9
+ rubocop-shopify: rubocop.yml
10
+
11
+ AllCops:
12
+ TargetRubyVersion: 3.3
13
+ TargetRailsVersion: 7.1
14
+ NewCops: enable
15
+ Exclude:
16
+ - "active_fields.gemspec"
17
+
18
+ Layout/EmptyLinesAroundAccessModifier:
19
+ EnforcedStyle: around
20
+
21
+ Layout/IndentationConsistency:
22
+ EnforcedStyle: normal
23
+
24
+ Style/SymbolArray:
25
+ EnforcedStyle: percent
26
+
27
+ Style/WordArray:
28
+ EnforcedStyle: percent
29
+
30
+ Style/MethodCallWithArgsParentheses:
31
+ Enabled: false
32
+
33
+ Metrics/BlockLength:
34
+ Exclude:
35
+ - "spec/**/*"
36
+
37
+ RSpec/NestedGroups:
38
+ Max: 5
39
+
40
+ RSpec/ExampleLength:
41
+ Max: 10
42
+
43
+ RSpec/ContextWording:
44
+ Enabled: false
45
+
46
+ RSpec/MultipleExpectations:
47
+ Enabled: false
48
+
49
+ Rails/ApplicationRecord:
50
+ Enabled: false
51
+
52
+ Rails/Date:
53
+ Enabled: false
54
+
55
+ RSpec/FilePath:
56
+ Enabled: false
57
+
58
+ RSpec/SpecFilePathFormat:
59
+ Enabled: false
60
+
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-05-19
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 kirill@lassoid.ru. 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 LassoID
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,5 @@
1
+ # ActiveFields
2
+
3
+ [![Gem Version](https://img.shields.io/gem/v/active_fields?color=blue&label=version)](https://rubygems.org/gems/active_fields)
4
+ [![Gem downloads count](https://img.shields.io/gem/dt/active_fields)](https://rubygems.org/gems/active_fields)
5
+ [![Github Actions CI](https://github.com/lassoid/active_fields/actions/workflows/main.yml/badge.svg?branch=main)](https://github.com/lassoid/active_fields/actions/workflows/main.yml)
data/Rakefile ADDED
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveFields
4
+ module Casters
5
+ # Typecasts the active_value value
6
+ class BaseCaster
7
+ # To raw DB value
8
+ def serialize(value)
9
+ raise NotImplementedError
10
+ end
11
+
12
+ # From raw DB value
13
+ def deserialize(value)
14
+ raise NotImplementedError
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "base_caster"
4
+
5
+ module ActiveFields
6
+ module Casters
7
+ class BooleanCaster < BaseCaster
8
+ def serialize(value)
9
+ cast(value)
10
+ end
11
+
12
+ def deserialize(value)
13
+ cast(value)
14
+ end
15
+
16
+ private
17
+
18
+ def cast(value)
19
+ ActiveModel::Type::Boolean.new.cast(value)
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "date_caster"
4
+
5
+ module ActiveFields
6
+ module Casters
7
+ class DateArrayCaster < DateCaster
8
+ def serialize(value)
9
+ return unless value.is_a?(Array)
10
+
11
+ value.map { super(_1) }
12
+ end
13
+
14
+ def deserialize(value)
15
+ return unless value.is_a?(Array)
16
+
17
+ value.map { super(_1) }
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "base_caster"
4
+
5
+ module ActiveFields
6
+ module Casters
7
+ class DateCaster < BaseCaster
8
+ def serialize(value)
9
+ cast(value)&.iso8601
10
+ end
11
+
12
+ def deserialize(value)
13
+ cast(value)
14
+ end
15
+
16
+ private
17
+
18
+ def cast(value)
19
+ casted_value = ActiveModel::Type::Date.new.cast(value)
20
+
21
+ casted_value if casted_value.acts_like?(:date)
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "decimal_caster"
4
+
5
+ module ActiveFields
6
+ module Casters
7
+ class DecimalArrayCaster < DecimalCaster
8
+ def serialize(value)
9
+ return unless value.is_a?(Array)
10
+
11
+ value.map { super(_1) }
12
+ end
13
+
14
+ def deserialize(value)
15
+ return unless value.is_a?(Array)
16
+
17
+ value.map { super(_1) }
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "base_caster"
4
+
5
+ module ActiveFields
6
+ module Casters
7
+ class DecimalCaster < BaseCaster
8
+ def serialize(value)
9
+ cast(value)
10
+ end
11
+
12
+ def deserialize(value)
13
+ cast(value)
14
+ end
15
+
16
+ private
17
+
18
+ def cast(value)
19
+ BigDecimal(value, 0, exception: false)
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "text_array_caster"
4
+
5
+ module ActiveFields
6
+ module Casters
7
+ class EnumArrayCaster < TextArrayCaster; end
8
+ end
9
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "text_caster"
4
+
5
+ module ActiveFields
6
+ module Casters
7
+ class EnumCaster < TextCaster; end
8
+ end
9
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "integer_caster"
4
+
5
+ module ActiveFields
6
+ module Casters
7
+ class IntegerArrayCaster < IntegerCaster
8
+ def serialize(value)
9
+ return unless value.is_a?(Array)
10
+
11
+ value.map { super(_1) }
12
+ end
13
+
14
+ def deserialize(value)
15
+ return unless value.is_a?(Array)
16
+
17
+ value.map { super(_1) }
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "base_caster"
4
+
5
+ module ActiveFields
6
+ module Casters
7
+ class IntegerCaster < DecimalCaster
8
+ def serialize(value)
9
+ cast(value)
10
+ end
11
+
12
+ def deserialize(value)
13
+ cast(value)
14
+ end
15
+
16
+ private
17
+
18
+ def cast(value)
19
+ super(value)&.to_i
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "text_caster"
4
+
5
+ module ActiveFields
6
+ module Casters
7
+ class TextArrayCaster < TextCaster
8
+ def serialize(value)
9
+ return unless value.is_a?(Array)
10
+
11
+ value.map { super(_1) }
12
+ end
13
+
14
+ def deserialize(value)
15
+ return unless value.is_a?(Array)
16
+
17
+ value.map { super(_1) }
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "base_caster"
4
+
5
+ module ActiveFields
6
+ module Casters
7
+ class TextCaster < BaseCaster
8
+ def serialize(value)
9
+ cast(value)
10
+ end
11
+
12
+ def deserialize(value)
13
+ cast(value)
14
+ end
15
+
16
+ private
17
+
18
+ def cast(value)
19
+ value&.to_s
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Mix-in that provides ActiveRecord models with active fields functionality
4
+ module ActiveFields
5
+ module Concern
6
+ extend ActiveSupport::Concern
7
+
8
+ class_methods do
9
+ def has_active_fields(options = {})
10
+ include ActiveFields::Customizable
11
+
12
+ @__active_fields_options__ = options.dup
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Mix-in that adds the active fields functionality to the ActiveRecord model
4
+ module ActiveFields
5
+ module Customizable
6
+ extend ActiveSupport::Concern
7
+
8
+ included do
9
+ # active_values association for the owner record.
10
+ # We skip built-in autosave because it doesn't work if the owner record isn't changed.
11
+ # Instead, we implement our own autosave callback: `save_changed_active_values`.
12
+ has_many :active_values,
13
+ class_name: "ActiveFields::Value",
14
+ as: :customizable,
15
+ inverse_of: :customizable,
16
+ autosave: false,
17
+ dependent: :destroy
18
+
19
+ # Firstly, we build active_values that hasn't been already created.
20
+ # Than, we set values for active_values whose values should be changed
21
+ # according to `active_values_attributes`.
22
+ before_validation :initialize_active_values
23
+
24
+ # Save all changed active_values on the owner record save.
25
+ after_save :save_changed_active_values
26
+
27
+ # We always validate active_values on the owner record change,
28
+ # as if they are just an ordinary record columns.
29
+ validates_associated :active_values
30
+
31
+ # This virtual attribute is used for setting active_values values.
32
+ # Keys are active_fields names,
33
+ # values are values for corresponding active_values of the record.
34
+ attr_reader :active_values_attributes
35
+ end
36
+
37
+ def active_fields
38
+ ActiveFields::Field.for(model_name.name)
39
+ end
40
+
41
+ # Convert hash keys to strings for easier access by fields names.
42
+ def active_values_attributes=(value)
43
+ @active_values_attributes =
44
+ if value.respond_to?(:to_h)
45
+ value.to_h.transform_keys(&:to_s)
46
+ else
47
+ value
48
+ end
49
+ end
50
+
51
+ private
52
+
53
+ def initialize_active_values
54
+ active_fields.each do |active_field|
55
+ active_value =
56
+ find_active_value_by_field(active_field) ||
57
+ active_values.new(active_field: active_field, value: active_field.default_value)
58
+
59
+ next unless active_values_attributes.is_a?(Hash)
60
+ next unless active_values_attributes.key?(active_field.name)
61
+
62
+ active_value.value = active_values_attributes[active_field.name]
63
+ end
64
+ end
65
+
66
+ def save_changed_active_values
67
+ active_values.each do |active_value|
68
+ next unless active_value.new_record? || active_value.changed?
69
+
70
+ # For new records association id isn't set right, so we force reassignment of the customizable
71
+ active_value.customizable = self
72
+
73
+ # Do not validate active values twice,
74
+ # because they have already been validated by `validates_associated`.
75
+ active_value.save!(validate: false)
76
+ end
77
+ end
78
+
79
+ def find_active_value_by_field(active_field)
80
+ active_values.find { |active_value| active_value.active_field_id == active_field.id }
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Mix-in with a base logic for the active fields model
4
+ module ActiveFields
5
+ module FieldConcern
6
+ extend ActiveSupport::Concern
7
+
8
+ included do
9
+ has_many :active_values,
10
+ class_name: "ActiveFields::Value",
11
+ foreign_key: :active_field_id,
12
+ inverse_of: :active_field,
13
+ dependent: :destroy
14
+
15
+ scope :for, ->(customizable_type) { where(customizable_type: customizable_type) }
16
+
17
+ validates :type, presence: true
18
+ validates :name, presence: true, uniqueness: { scope: :customizable_type }
19
+ validates :name, format: { with: /\A[a-z0-9_]+\z/ }, allow_blank: true
20
+ validate :validate_default_value
21
+
22
+ after_create :add_field_to_records
23
+ after_initialize :set_defaults
24
+ end
25
+
26
+ def value_validator_class
27
+ @value_validator_class ||= "ActiveFields::Validators::#{model_name.name.demodulize}Validator".constantize
28
+ end
29
+
30
+ def value_validator
31
+ value_validator_class.new(self)
32
+ end
33
+
34
+ def value_caster_class
35
+ @value_caster_class ||= "ActiveFields::Casters::#{model_name.name.demodulize}Caster".constantize
36
+ end
37
+
38
+ def value_caster
39
+ value_caster_class.new
40
+ end
41
+
42
+ def customizable_model
43
+ customizable_type.constantize
44
+ end
45
+
46
+ def default_value=(v)
47
+ super(value_caster.serialize(v))
48
+ end
49
+
50
+ def default_value
51
+ value_caster.deserialize(super)
52
+ end
53
+
54
+ private
55
+
56
+ def validate_default_value
57
+ validator = value_validator
58
+ return if validator.validate(default_value)
59
+
60
+ validator.errors.each do |error|
61
+ if error.is_a?(Array) && error.size == 2 && error.first.is_a?(Symbol) && error.last.is_a?(Hash)
62
+ errors.add(:default_value, error.first, **error.last)
63
+ elsif error.is_a?(Symbol)
64
+ errors.add(:default_value, *error)
65
+ else
66
+ raise ArgumentError
67
+ end
68
+ end
69
+ end
70
+
71
+ def add_field_to_records
72
+ customizable_model.find_each do |record|
73
+ ActiveFields::Value.create!(active_field: self, customizable: record, value: default_value)
74
+ end
75
+ end
76
+
77
+ def set_defaults; end
78
+ end
79
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Mix-in with a base logic for the active fields value model
4
+ module ActiveFields
5
+ module ValueConcern
6
+ extend ActiveSupport::Concern
7
+
8
+ included do
9
+ belongs_to :customizable, polymorphic: true, optional: false, inverse_of: :active_values
10
+ belongs_to :active_field, class_name: "ActiveFields::Field", optional: false, inverse_of: :active_values
11
+
12
+ validates :active_field_id, uniqueness: { scope: %i[customizable_id customizable_type] }
13
+ validate :validate_value
14
+ validate :validate_customizable_allowed
15
+ end
16
+
17
+ def value=(v)
18
+ super(active_field&.value_caster&.serialize(v))
19
+ end
20
+
21
+ def value
22
+ active_field&.value_caster&.deserialize(super)
23
+ end
24
+
25
+ private
26
+
27
+ def validate_value
28
+ return if (validator = active_field&.value_validator).nil?
29
+ return if validator.validate(value)
30
+
31
+ validator.errors.each do |error|
32
+ if error.is_a?(Array) && error.size == 2 && error.first.is_a?(Symbol) && error.last.is_a?(Hash)
33
+ errors.add(:value, error.first, **error.last)
34
+ elsif error.is_a?(Symbol)
35
+ errors.add(:value, *error)
36
+ else
37
+ raise ArgumentError
38
+ end
39
+ end
40
+ end
41
+
42
+ def validate_customizable_allowed
43
+ return true if active_field.nil?
44
+ return true if customizable_type == active_field.customizable_type
45
+
46
+ errors.add(:customizable, :invalid)
47
+ false
48
+ end
49
+ end
50
+ end