expectant 0.1.0 → 0.3.1

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f7c8fb47dd089d48a02b00fb0c106265f4a96b8f6d66915291cbbf22bb0b99fd
4
- data.tar.gz: b44f3f15b5c63e07ae4d50ca2befec46359a35120df9e9ac237250cbc6d7c625
3
+ metadata.gz: 06e38c364b8d2d666a81174ddafa2b426153ce1627c155bd996c8b1a912c6212
4
+ data.tar.gz: 7d5d662b9971375813d280f5c129aeb0ec80d960b5520368063714c7057ce794
5
5
  SHA512:
6
- metadata.gz: a364cf6475de054400a7c3a764eca3eccbe4200cac42a886bcc2e4fe22c3ac1e5846a66aa5a285acaaf04f103cfa40595d838681b5fd7423c31e7d1d3baffeaf
7
- data.tar.gz: 96869a7a4aca6edf679c1247a6e7514d92ecadba0f5805ea920c9368f878fb074a34890092b771d1247a730d88052bc5bbdfa3e334ce8c8229df2add794daa4a
6
+ metadata.gz: 04545df86e467ffcb8bd6c48f8cb702f90527ef5f9c5bf745d265bcc95ab80f84a606dafec9b57a345058d148ad61f7e7702476cbcc749d5471ed9ca7b5e2d7f
7
+ data.tar.gz: 7c427ebfc893ee72957783526adba4189f23e032f08c574ae9785932f01ac783cc7d0a4ae25a64743b5529d8c324ae966e1330ff79be3f869383c6ef796d5680
data/.rspec CHANGED
@@ -1,3 +1,3 @@
1
- --format documentation
2
- --color
3
- --require spec_helper
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.standard.yml CHANGED
@@ -1,3 +1,3 @@
1
- # For available configuration options, see:
2
- # https://github.com/standardrb/standard
3
- ruby_version: 3.1
1
+ # For available configuration options, see:
2
+ # https://github.com/standardrb/standard
3
+ ruby_version: 3.1
data/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
- ## [Unreleased]
2
-
3
- ## [0.1.0] - 2025-10-02
4
-
5
- - Initial release
1
+ ## [Unreleased]
2
+
3
+ ## [0.3.0] - 2025-10-09
4
+
5
+ - Re-wrote the API for simplicity
6
+
7
+ ## [0.1.0] - 2025-10-02
8
+
9
+ - Initial release
data/LICENSE.txt CHANGED
@@ -1,21 +1,21 @@
1
- The MIT License (MIT)
2
-
3
- Copyright (c) 2025 Javi Medina Fetterman
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.
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Hector Medina Fetterman
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 CHANGED
@@ -1,43 +1,152 @@
1
- # Expectant
2
-
3
- TODO: Delete this and the text below, and describe your gem
4
-
5
- Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/expectant`. To experiment with that code, run `bin/console` for an interactive prompt.
6
-
7
- ## Installation
8
-
9
- TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
-
11
- Install the gem and add to the application's Gemfile by executing:
12
-
13
- ```bash
14
- bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
15
- ```
16
-
17
- If bundler is not being used to manage dependencies, install the gem by executing:
18
-
19
- ```bash
20
- gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
21
- ```
22
-
23
- ## Usage
24
-
25
- TODO: Write usage instructions here
26
-
27
- ## Development
28
-
29
- After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
-
31
- To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
-
33
- ## Contributing
34
-
35
- Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/expectant. 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/[USERNAME]/expectant/blob/master/CODE_OF_CONDUCT.md).
36
-
37
- ## License
38
-
39
- The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
40
-
41
- ## Code of Conduct
42
-
43
- Everyone interacting in the Expectant project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/expectant/blob/master/CODE_OF_CONDUCT.md).
1
+ # Expectant
2
+
3
+ [![Gem Version](https://img.shields.io/gem/v/expectant?style=flat&label=Expectant)](https://rubygems.org/gems/expectant)
4
+ [![Ruby Test](https://github.com/DigitalHospital/expectant/actions/workflows/main.yml/badge.svg?branch=master)](https://github.com/expectant/actions/workflows/main.yml)</span>
5
+
6
+ A Ruby DSL for defining validation schemas with type coercion, defaults, and fallbacks. Built on [dry-validation](https://dry-rb.org/gems/dry-validation/) and [dry-types](https://dry-rb.org/gems/dry-types/).
7
+
8
+ ## Installation
9
+
10
+ ```ruby
11
+ gem 'expectant'
12
+ ```
13
+
14
+ ## Quick Start
15
+
16
+ ```ruby
17
+ class InvoiceService
18
+ include Expectant::DSL
19
+
20
+ expects :inputs
21
+
22
+ input :customer_id, type: :integer
23
+ input :amount, type: :float
24
+ input :status, type: :string, default: "draft"
25
+ input :description, type: :string, optional: true
26
+
27
+ input_rule(:amount) do
28
+ key.failure("must be positive") if value && value <= 0
29
+ end
30
+
31
+ def process(data)
32
+ result = inputs.validate(data)
33
+
34
+ if result.success?
35
+ # Use validated data: result.to_h
36
+ else
37
+ # Handle errors: result.errors.to_h
38
+ end
39
+ end
40
+ end
41
+ ```
42
+
43
+ ## Core Features
44
+
45
+ ### Types
46
+
47
+ ```ruby
48
+ expects :inputs
49
+
50
+ input :name, type: :string
51
+ input :age, type: :integer
52
+ input :price, type: :float
53
+ input :active, type: :boolean
54
+ input :date, type: :date
55
+ input :time, type: :datetime
56
+ input :data, type: :hash
57
+ input :tags, type: :array
58
+ input :user, type: User # Custom class
59
+ ```
60
+
61
+ ### Defaults and Optional Fields
62
+
63
+ ```ruby
64
+ # Optional (can be omitted)
65
+ input :description, type: :string, optional: true
66
+
67
+ # Static default
68
+ input :status, type: :string, default: "draft"
69
+
70
+ # Dynamic default (proc)
71
+ input :created_at, type: :datetime, default: -> { Time.now }
72
+ ```
73
+
74
+ ### Fallbacks
75
+
76
+ Automatically substitute values when validation fails:
77
+
78
+ ```ruby
79
+ input :per_page, type: :integer, default: 25, fallback: 25
80
+
81
+ input_rule(:per_page) do
82
+ key.failure("max 100") if value && value > 100
83
+ end
84
+
85
+ # If per_page: 500 is provided, validation succeeds with fallback value 25
86
+ ```
87
+
88
+ ### Validation Rules
89
+
90
+ ```ruby
91
+ # Single field
92
+ input_rule(:email) do
93
+ key.failure("invalid") unless value&.include?("@")
94
+ end
95
+
96
+ # Multiple fields
97
+ input_rule(:start_date, :end_date) do
98
+ base.failure("start must be before end") if values[:start_date] > values[:end_date]
99
+ end
100
+
101
+ # Global rule
102
+ input_rule do
103
+ base.failure("error") if some_condition
104
+ end
105
+ ```
106
+
107
+ ### Context
108
+
109
+ ```ruby
110
+ input_rule(:order) do
111
+ valid = context[:orderable_columns] || []
112
+ key.failure("invalid column") unless valid.include?(value)
113
+ end
114
+
115
+ # Pass context when validating
116
+ inputs.validate(data, context: { orderable_columns: ["id", "name"] })
117
+ ```
118
+
119
+ ### Multiple Schemas
120
+
121
+ ```ruby
122
+ expects :inputs
123
+ expects :outputs
124
+
125
+ input :data, type: :hash
126
+ output :result, type: :string
127
+
128
+ inputs.validate(input_data)
129
+ outputs.validate(output_data)
130
+ ```
131
+
132
+ ## Configuration
133
+
134
+ Customize validator method names:
135
+
136
+ ```ruby
137
+ Expectant.configure do |config|
138
+ config.validator_suffix = "validation" # input_validation instead of input_rule
139
+ config.validator_prefix = "validate" # validate_input
140
+ end
141
+ ```
142
+
143
+ ## Development
144
+
145
+ ```bash
146
+ bundle install
147
+ bundle exec rspec
148
+ ```
149
+
150
+ ## License
151
+
152
+ MIT License
data/Rakefile CHANGED
@@ -1,10 +1,10 @@
1
- # frozen_string_literal: true
2
-
3
- require "bundler/gem_tasks"
4
- require "rspec/core/rake_task"
5
-
6
- RSpec::Core::RakeTask.new(:spec)
7
-
8
- require "standard/rake"
9
-
10
- task default: %i[spec standard]
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "standard/rake"
9
+
10
+ task default: %i[spec standard]
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Expectant
4
+ # Instance-bound schema wrapper that provides validation with instance context
5
+ class BoundSchema
6
+ def initialize(instance, schema)
7
+ @instance = instance
8
+ @schema = schema
9
+ end
10
+
11
+ def validate(data, context: {})
12
+ # Apply proc defaults before validation
13
+ data = apply_defaults(data)
14
+
15
+ # Create contract instance with context, then validate
16
+ contract_class = @schema.contract
17
+ contract = contract_class.new(instance: @instance, context: context)
18
+ result = contract.call(data)
19
+
20
+ # If validation failed, apply fallbacks for fields with errors and retry
21
+ if !result.success?
22
+ data_with_fallbacks = apply_fallbacks(data, result)
23
+ if data_with_fallbacks != data
24
+ # Re-validate with fallback values
25
+ result = contract.call(data_with_fallbacks)
26
+ end
27
+ end
28
+
29
+ result
30
+ end
31
+
32
+ def keys
33
+ @schema.keys
34
+ end
35
+
36
+ def contract
37
+ @schema.contract
38
+ end
39
+
40
+ private
41
+
42
+ # Apply default values for missing fields (especially proc defaults)
43
+ def apply_defaults(data)
44
+ data = data.dup
45
+
46
+ @schema.fields.each do |field|
47
+ # Skip if value already provided
48
+ next if data.key?(field.name)
49
+
50
+ # Apply proc defaults, static defaults are handled by dry-types
51
+ if field.default.respond_to?(:call)
52
+ data[field.name] = @instance.instance_exec(&field.default)
53
+ end
54
+ end
55
+
56
+ data
57
+ end
58
+
59
+ # Apply fallback values to fields that have errors
60
+ def apply_fallbacks(data, result)
61
+ data = data.dup
62
+
63
+ @schema.fields.each do |field|
64
+ next unless field.has_fallback?
65
+
66
+ # Apply fallback if field has an error
67
+ if result.errors[field.name]&.any?
68
+ fallback_value = if field.fallback.respond_to?(:call)
69
+ # Proc fallback - evaluate in instance context
70
+ @instance.instance_exec(&field.fallback)
71
+ else
72
+ field.fallback
73
+ end
74
+ data[field.name] = fallback_value
75
+ end
76
+ end
77
+
78
+ data
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Expectant
4
+ class Configuration
5
+ attr_accessor :validator_prefix, :validator_suffix
6
+
7
+ def initialize
8
+ @validator_prefix = nil # default: no prefix
9
+ @validator_suffix = "rule" # default: schema_name_rule
10
+ end
11
+ end
12
+ end
data/lib/expectant/dsl.rb CHANGED
@@ -1,77 +1,120 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "utils"
4
+ require_relative "schema"
5
+ require_relative "bound_schema"
6
+
3
7
  module Expectant
4
8
  module DSL
5
- def self.extended(base)
6
- base.class_eval do
7
- @schemas = {}
8
- @schema_definitions = {}
9
- end
9
+ def self.included(base)
10
+ base.include(Types)
11
+ base.extend(ClassMethods)
10
12
  end
11
13
 
12
- # Define a new schema type (e.g., :expects, :promises, :params, :outputs)
13
- def expectation(schema_name)
14
- schema_name = schema_name.to_sym
15
- (@schema_definitions ||= {})[schema_name] = {
16
- fields: [],
17
- rules: []
18
- }
14
+ module ClassMethods
15
+ def self.extended(base)
16
+ base.class_eval do
17
+ @_expectant_schemas = {}
18
+ end
19
+ end
19
20
 
20
- # Dynamically define the field definition method (e.g., expects, promises)
21
- define_singleton_method(schema_name) do |name, **options|
22
- expectation = Expectation.new(name, **options)
23
- @schema_definitions[schema_name][:fields] << expectation
21
+ def inherited(sub)
22
+ return unless instance_variable_defined?(:@_expectant_schemas)
23
+ return if @_expectant_schemas.empty?
24
24
 
25
- # Define attribute accessor
26
- attr_accessor name
25
+ # Deep copy each schema (fields + validators)
26
+ parent_schemas = @_expectant_schemas
27
+ duped = parent_schemas.transform_values { |schema| schema.duplicate }
27
28
 
28
- expectation
29
+ sub.instance_variable_set(:@_expectant_schemas, duped)
29
30
  end
30
31
 
31
- # Dynamically define the rule method (e.g., expects_rule, promises_rule)
32
- rule_method_name = "#{schema_name}_rule"
33
- define_singleton_method(rule_method_name) do |*field_names, &block|
34
- @schema_definitions[schema_name][:rules] << {
35
- name: field_names.empty? ? nil : (field_names.size == 1 ? field_names.first : field_names),
36
- block: block
37
- }
32
+ # Define a new expectation schema
33
+ # Options:
34
+ # collision: :error|:force -> method name collision policy for dynamic definitions
35
+ # singular: string|symbol -> control singular name for the schema
36
+ def expects(schema_name, collision: :error, singular: nil)
37
+ field_method_name = Utils.singularize(schema_name.to_sym)
38
+ if !singular.nil?
39
+ if singular.is_a?(String) || singular.is_a?(Symbol)
40
+ field_method_name = singular.to_sym
41
+ else
42
+ raise ConfigurationError, "Invalid singular option: #{singular.inspect}"
43
+ end
44
+ end
45
+ schema = schema_name.to_sym
46
+
47
+ if @_expectant_schemas.key?(schema)
48
+ raise SchemaError, "Schema :#{schema} already defined"
49
+ else
50
+ create_schema(schema, collision: collision, field_method_name: field_method_name)
51
+ end
52
+
53
+ self
38
54
  end
39
- end
40
55
 
41
- # Get the schema definition for a given schema name
42
- def schema_definitions
43
- @schema_definitions ||= {}
44
- end
56
+ def reset_inherited_expectations!
57
+ @_expectant_schemas = {}
58
+ end
45
59
 
46
- # Build and return a dry-schema for a specific schema type
47
- def get_schema(schema_name)
48
- schema_name = schema_name.to_sym
49
- (@schemas ||= {})[schema_name] ||= SchemaBuilder.new(
50
- schema_definitions[schema_name]
51
- ).build
52
- end
60
+ private
53
61
 
54
- # Validate data against a specific schema
55
- def validate(schema_name, data)
56
- get_schema(schema_name).call(data)
57
- end
62
+ def create_schema(schema_name, collision: :error, field_method_name: nil)
63
+ @_expectant_schemas[schema_name] = Schema.new(schema_name)
58
64
 
59
- def new(*args, **kwargs)
60
- instance = super(*args, **kwargs)
61
-
62
- # Set default values for all schema fields
63
- schema_definitions.each do |_schema_name, definition|
64
- definition[:fields].each do |expectation|
65
- if expectation.default
66
- default_value = expectation.default.respond_to?(:call) ?
67
- expectation.default.call :
68
- expectation.default
69
- instance.send("#{expectation.name}=", default_value)
65
+ # Dynamically define the field definition method
66
+ # (e.g. input for :inputs, datum for :data)
67
+ Utils.define_with_collision_policy(singleton_class, field_method_name, collision: collision) do
68
+ define_singleton_method(field_method_name) do |name, **options|
69
+ expectation = Expectation.new(name, **options)
70
+ @_expectant_schemas[schema_name].add_field(expectation)
71
+ expectation
72
+ end
73
+ end
74
+
75
+ # Reset a schema
76
+ reset_method_name = "reset_#{schema_name}!"
77
+ Utils.define_with_collision_policy(singleton_class, reset_method_name, collision: collision) do
78
+ define_singleton_method(reset_method_name) do
79
+ @_expectant_schemas[schema_name].reset!
80
+ end
81
+ end
82
+
83
+ # Define validators
84
+ method_name = Utils.validator_method_name(field_method_name, Expectant.configuration)
85
+ Utils.define_with_collision_policy(singleton_class, method_name, collision: collision) do
86
+ define_singleton_method(method_name) do |*field_names, &block|
87
+ @_expectant_schemas[schema_name].add_validator({
88
+ name: if field_names.empty?
89
+ nil
90
+ else
91
+ ((field_names.size == 1) ? field_names.first : field_names)
92
+ end,
93
+ block: block
94
+ })
70
95
  end
71
96
  end
72
- end
73
97
 
74
- instance
98
+ # Add class-level schema accessor method (e.g. MyClass.inputs)
99
+ Utils.define_with_collision_policy(singleton_class, schema_name, collision: collision) do
100
+ define_singleton_method(schema_name) do
101
+ @_expectant_schemas[schema_name]
102
+ end
103
+ end
104
+
105
+ # Add instance-level schema accessor method (e.g. instance.inputs)
106
+ if !instance_methods(false).include?(schema_name)
107
+ define_method(schema_name) do
108
+ BoundSchema.new(self, self.class.instance_variable_get(:@_expectant_schemas)[schema_name])
109
+ end
110
+ elsif collision == :force
111
+ define_method(schema_name) do
112
+ BoundSchema.new(self, self.class.instance_variable_get(:@_expectant_schemas)[schema_name])
113
+ end
114
+ elsif collision == :error
115
+ raise ConfigurationError, "Instance method #{schema_name} already defined"
116
+ end
117
+ end
75
118
  end
76
119
  end
77
- end
120
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Expectant
4
+ class Error < StandardError; end
5
+ class ConfigurationError < Error; end
6
+ class SchemaError < Error; end
7
+ class ValidationError < Error; end
8
+ end
@@ -2,65 +2,36 @@
2
2
 
3
3
  module Expectant
4
4
  class Expectation
5
- attr_reader :name, :type, :optional, :default
5
+ attr_reader :name, :type, :dry_type, :fallback, :default, :metadata
6
6
 
7
- def initialize(name, type: nil, optional: false, default: nil, **options)
7
+ def initialize(name, type: nil, default: nil, optional: false, fallback: nil, **options)
8
8
  @name = name
9
9
  @type = type
10
- @optional = optional
11
10
  @default = default
12
- @options = options
11
+ @fallback = fallback
12
+ @metadata = options
13
+
14
+ base_type = Types.resolve(type)
15
+ base_type = base_type.optional if optional
16
+ # if default is a proc, we call it at runtime
17
+ @dry_type = if !default.nil? && !default.respond_to?(:call)
18
+ base_type.default(default)
19
+ else
20
+ base_type
21
+ end
13
22
  end
14
23
 
24
+ # A field is required if it's not optional and has no default
15
25
  def required?
16
- !optional && default.nil?
26
+ !@dry_type.optional? && !has_default?
17
27
  end
18
28
 
19
29
  def has_default?
20
- !default.nil?
30
+ @dry_type.default? || !@default.nil?
21
31
  end
22
32
 
23
- def type_class
24
- case type
25
- when :integer, :int
26
- Integer
27
- when :float
28
- Float
29
- when :string, :str
30
- String
31
- when :boolean, :bool
32
- [TrueClass, FalseClass]
33
- when :array
34
- Array
35
- when :hash
36
- Hash
37
- when Class
38
- type
39
- else
40
- nil
41
- end
42
- end
43
-
44
- def dry_validation_type
45
- case type
46
- when :integer, :int
47
- :integer
48
- when :float
49
- :float
50
- when :string, :str
51
- :string
52
- when :boolean, :bool
53
- :bool
54
- when :array
55
- :array
56
- when :hash
57
- :hash
58
- when Class
59
- # For custom classes, we'll use :any and add custom validation
60
- :any
61
- else
62
- :any
63
- end
33
+ def has_fallback?
34
+ !@fallback.nil?
64
35
  end
65
36
  end
66
- end
37
+ end
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry/validation"
4
+
5
+ module Expectant
6
+ class Schema
7
+ attr_reader :name, :fields, :validators
8
+
9
+ def initialize(name)
10
+ @name = name
11
+ @fields = []
12
+ @validators = []
13
+ @contract_class = nil
14
+ end
15
+
16
+ def keys
17
+ @fields.map(&:name)
18
+ end
19
+
20
+ def contract
21
+ @contract_class ||= build_contract
22
+ end
23
+
24
+ def duplicate
25
+ dup = self.class.new(@name)
26
+ dup.instance_variable_set(:@fields, @fields.dup)
27
+ dup.instance_variable_set(:@validators, @validators.dup)
28
+ dup
29
+ end
30
+
31
+ def add_field(expectation)
32
+ @fields << expectation
33
+ @contract_class = nil
34
+ end
35
+
36
+ def add_validator(validator_def)
37
+ @validators << validator_def
38
+ @contract_class = nil
39
+ end
40
+
41
+ def freeze
42
+ @fields.freeze
43
+ @validators.freeze
44
+ super
45
+ end
46
+
47
+ def reset!
48
+ @fields = []
49
+ @validators = []
50
+ @contract_class = nil
51
+ end
52
+
53
+ private
54
+
55
+ def build_contract
56
+ fields = @fields
57
+ validators = @validators
58
+
59
+ Class.new(Dry::Validation::Contract) do
60
+ # Enable option passing (allows context and instance to be passed at validation time)
61
+ option :context, default: proc { {} }
62
+ option :instance, optional: true
63
+
64
+ # Define schema based on fields using dry-types
65
+ params do
66
+ fields.each do |field|
67
+ dry_type = field.dry_type
68
+
69
+ if field.required?
70
+ required(field.name).value(dry_type)
71
+ else
72
+ optional(field.name).value(dry_type)
73
+ end
74
+ end
75
+ end
76
+
77
+ # Add custom validators
78
+ validators.each do |validator_def|
79
+ if validator_def[:name]
80
+ # Single key or multiple keys
81
+ if validator_def[:name].is_a?(Array)
82
+ rule(*validator_def[:name], &validator_def[:block])
83
+ else
84
+ rule(validator_def[:name], &validator_def[:block])
85
+ end
86
+ else
87
+ # Global rule without a specific field
88
+ rule(&validator_def[:block])
89
+ end
90
+ end
91
+ end
92
+ end
93
+ end
94
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry-types"
4
+
5
+ module Expectant
6
+ module Types
7
+ include Dry.Types()
8
+
9
+ def self.resolve(type_definition)
10
+ case type_definition
11
+ when nil
12
+ Any
13
+ when Symbol
14
+ resolve_symbol(type_definition)
15
+ when Dry::Types::Type
16
+ # Already a dry-type, return as-is
17
+ type_definition
18
+ when Class
19
+ Instance(type_definition)
20
+ else
21
+ raise ConfigurationError, "Invalid type definition: #{type_definition}"
22
+ end
23
+ end
24
+
25
+ def self.resolve_symbol(symbol)
26
+ case symbol
27
+ when :string, :str
28
+ Params::String
29
+ when :integer, :int
30
+ Params::Integer
31
+ when :float
32
+ Params::Float
33
+ when :decimal
34
+ Params::Decimal
35
+ when :boolean, :bool
36
+ Params::Bool
37
+ when :date
38
+ Params::Date
39
+ when :datetime
40
+ Params::DateTime
41
+ when :time
42
+ Params::Time
43
+ when :array
44
+ Params::Array
45
+ when :hash
46
+ Params::Hash
47
+ when :symbol, :sym
48
+ Symbol
49
+ when :any, :nil
50
+ Any
51
+ else
52
+ raise ConfigurationError, "Unknown type symbol: #{symbol}"
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/inflector"
4
+
5
+ module Expectant
6
+ module Utils
7
+ module_function
8
+
9
+ def singularize(word)
10
+ ActiveSupport::Inflector.singularize(word.to_s).to_sym
11
+ end
12
+
13
+ def validator_method_name(schema_name, configuration)
14
+ prefix = configuration.validator_prefix
15
+ suffix = configuration.validator_suffix
16
+
17
+ parts = []
18
+ parts << prefix if prefix
19
+ parts << schema_name
20
+ parts << suffix if suffix
21
+
22
+ parts.join("_")
23
+ end
24
+
25
+ def define_with_collision_policy(target, method_name, collision:, &block)
26
+ method_name = method_name.to_sym
27
+ if target.method_defined?(method_name) || target.private_method_defined?(method_name)
28
+ case collision
29
+ when :error
30
+ raise ConfigurationError, "Method #{method_name} already defined"
31
+ when :force
32
+ begin
33
+ target.send(:remove_method, method_name)
34
+ rescue
35
+ nil
36
+ end
37
+ block.call
38
+ else
39
+ raise ConfigurationError, "Unknown collision policy: #{collision}"
40
+ end
41
+ else
42
+ block.call
43
+ end
44
+ end
45
+ end
46
+ end
@@ -1,5 +1,5 @@
1
- # frozen_string_literal: true
2
-
3
- module Expectant
4
- VERSION = "0.1.0"
5
- end
1
+ # frozen_string_literal: true
2
+
3
+ module Expectant
4
+ VERSION = "0.3.1"
5
+ end
data/lib/expectant.rb CHANGED
@@ -1,14 +1,26 @@
1
- # frozen_string_literal: true
2
-
3
- require_relative "expectant/version"
4
- require_relative "expectant/dsl"
5
- require_relative "expectant/schema_builder"
6
- require_relative "expectant/expectation"
7
-
8
- module Expectant
9
- class Error < StandardError; end
10
-
11
- def self.included(base)
12
- base.extend(DSL)
13
- end
14
- end
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "expectant/version"
4
+ require_relative "expectant/errors"
5
+ require_relative "expectant/configuration"
6
+ require_relative "expectant/types"
7
+ require_relative "expectant/dsl"
8
+ require_relative "expectant/expectation"
9
+
10
+ module Expectant
11
+ class << self
12
+ attr_writer :configuration
13
+
14
+ def configuration
15
+ @configuration ||= Configuration.new
16
+ end
17
+
18
+ def configure
19
+ yield(configuration)
20
+ end
21
+
22
+ def reset_configuration!
23
+ @configuration = Configuration.new
24
+ end
25
+ end
26
+ end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: expectant
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.3.1
5
5
  platform: ruby
6
6
  authors:
7
- - Javi Medina Fetterman
7
+ - Hector Medina Fetterman
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2025-10-02 00:00:00.000000000 Z
11
+ date: 2026-03-15 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: dry-validation
@@ -24,7 +24,38 @@ dependencies:
24
24
  - - "~>"
25
25
  - !ruby/object:Gem::Version
26
26
  version: '1.10'
27
- description: Write a longer description or delete this line.
27
+ - !ruby/object:Gem::Dependency
28
+ name: dry-types
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.7'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.7'
41
+ - !ruby/object:Gem::Dependency
42
+ name: activesupport
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '6.0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '6.0'
55
+ description: Expectant provides a clean DSL for defining multiple validation schemas
56
+ in a single class. Built on dry-validation and dry-types, it supports custom rules,
57
+ defaults, fallbacks, and context-aware validations, making it easy to validate inputs,
58
+ outputs, and any structured data in your Ruby applications.
28
59
  email:
29
60
  - javi@digitalhospital.com
30
61
  executables: []
@@ -34,16 +65,19 @@ files:
34
65
  - ".rspec"
35
66
  - ".standard.yml"
36
67
  - CHANGELOG.md
37
- - CODE_OF_CONDUCT.md
38
68
  - LICENSE.txt
39
69
  - README.md
40
70
  - Rakefile
41
71
  - lib/expectant.rb
72
+ - lib/expectant/bound_schema.rb
73
+ - lib/expectant/configuration.rb
42
74
  - lib/expectant/dsl.rb
75
+ - lib/expectant/errors.rb
43
76
  - lib/expectant/expectation.rb
44
- - lib/expectant/schema_builder.rb
77
+ - lib/expectant/schema.rb
78
+ - lib/expectant/types.rb
79
+ - lib/expectant/utils.rb
45
80
  - lib/expectant/version.rb
46
- - sig/expectant.rbs
47
81
  homepage: https://github.com/DigitalHospital/expectant
48
82
  licenses:
49
83
  - MIT
@@ -66,8 +100,8 @@ required_rubygems_version: !ruby/object:Gem::Requirement
66
100
  - !ruby/object:Gem::Version
67
101
  version: '0'
68
102
  requirements: []
69
- rubygems_version: 3.4.10
103
+ rubygems_version: 3.4.19
70
104
  signing_key:
71
105
  specification_version: 4
72
- summary: Write a short summary, because RubyGems requires one.
106
+ summary: A flexible DSL for defining reusable validation schemas
73
107
  test_files: []
data/CODE_OF_CONDUCT.md DELETED
@@ -1,132 +0,0 @@
1
- # Contributor Covenant Code of Conduct
2
-
3
- ## Our Pledge
4
-
5
- We as members, contributors, and leaders pledge to make participation in our
6
- community a harassment-free experience for everyone, regardless of age, body
7
- size, visible or invisible disability, ethnicity, sex characteristics, gender
8
- identity and expression, level of experience, education, socio-economic status,
9
- nationality, personal appearance, race, caste, color, religion, or sexual
10
- identity and orientation.
11
-
12
- We pledge to act and interact in ways that contribute to an open, welcoming,
13
- diverse, inclusive, and healthy community.
14
-
15
- ## Our Standards
16
-
17
- Examples of behavior that contributes to a positive environment for our
18
- community include:
19
-
20
- * Demonstrating empathy and kindness toward other people
21
- * Being respectful of differing opinions, viewpoints, and experiences
22
- * Giving and gracefully accepting constructive feedback
23
- * Accepting responsibility and apologizing to those affected by our mistakes,
24
- and learning from the experience
25
- * Focusing on what is best not just for us as individuals, but for the overall
26
- community
27
-
28
- Examples of unacceptable behavior include:
29
-
30
- * The use of sexualized language or imagery, and sexual attention or advances of
31
- any kind
32
- * Trolling, insulting or derogatory comments, and personal or political attacks
33
- * Public or private harassment
34
- * Publishing others' private information, such as a physical or email address,
35
- without their explicit permission
36
- * Other conduct which could reasonably be considered inappropriate in a
37
- professional setting
38
-
39
- ## Enforcement Responsibilities
40
-
41
- Community leaders are responsible for clarifying and enforcing our standards of
42
- acceptable behavior and will take appropriate and fair corrective action in
43
- response to any behavior that they deem inappropriate, threatening, offensive,
44
- or harmful.
45
-
46
- Community leaders have the right and responsibility to remove, edit, or reject
47
- comments, commits, code, wiki edits, issues, and other contributions that are
48
- not aligned to this Code of Conduct, and will communicate reasons for moderation
49
- decisions when appropriate.
50
-
51
- ## Scope
52
-
53
- This Code of Conduct applies within all community spaces, and also applies when
54
- an individual is officially representing the community in public spaces.
55
- Examples of representing our community include using an official email address,
56
- posting via an official social media account, or acting as an appointed
57
- representative at an online or offline event.
58
-
59
- ## Enforcement
60
-
61
- Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
- reported to the community leaders responsible for enforcement at
63
- [INSERT CONTACT METHOD].
64
- All complaints will be reviewed and investigated promptly and fairly.
65
-
66
- All community leaders are obligated to respect the privacy and security of the
67
- reporter of any incident.
68
-
69
- ## Enforcement Guidelines
70
-
71
- Community leaders will follow these Community Impact Guidelines in determining
72
- the consequences for any action they deem in violation of this Code of Conduct:
73
-
74
- ### 1. Correction
75
-
76
- **Community Impact**: Use of inappropriate language or other behavior deemed
77
- unprofessional or unwelcome in the community.
78
-
79
- **Consequence**: A private, written warning from community leaders, providing
80
- clarity around the nature of the violation and an explanation of why the
81
- behavior was inappropriate. A public apology may be requested.
82
-
83
- ### 2. Warning
84
-
85
- **Community Impact**: A violation through a single incident or series of
86
- actions.
87
-
88
- **Consequence**: A warning with consequences for continued behavior. No
89
- interaction with the people involved, including unsolicited interaction with
90
- those enforcing the Code of Conduct, for a specified period of time. This
91
- includes avoiding interactions in community spaces as well as external channels
92
- like social media. Violating these terms may lead to a temporary or permanent
93
- ban.
94
-
95
- ### 3. Temporary Ban
96
-
97
- **Community Impact**: A serious violation of community standards, including
98
- sustained inappropriate behavior.
99
-
100
- **Consequence**: A temporary ban from any sort of interaction or public
101
- communication with the community for a specified period of time. No public or
102
- private interaction with the people involved, including unsolicited interaction
103
- with those enforcing the Code of Conduct, is allowed during this period.
104
- Violating these terms may lead to a permanent ban.
105
-
106
- ### 4. Permanent Ban
107
-
108
- **Community Impact**: Demonstrating a pattern of violation of community
109
- standards, including sustained inappropriate behavior, harassment of an
110
- individual, or aggression toward or disparagement of classes of individuals.
111
-
112
- **Consequence**: A permanent ban from any sort of public interaction within the
113
- community.
114
-
115
- ## Attribution
116
-
117
- This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
- version 2.1, available at
119
- [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
-
121
- Community Impact Guidelines were inspired by
122
- [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
-
124
- For answers to common questions about this code of conduct, see the FAQ at
125
- [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
- [https://www.contributor-covenant.org/translations][translations].
127
-
128
- [homepage]: https://www.contributor-covenant.org
129
- [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
- [Mozilla CoC]: https://github.com/mozilla/diversity
131
- [FAQ]: https://www.contributor-covenant.org/faq
132
- [translations]: https://www.contributor-covenant.org/translations
@@ -1,86 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require 'dry/validation'
4
-
5
- module Expectant
6
- class SchemaBuilder
7
- def initialize(schema_definition)
8
- @fields = schema_definition[:fields]
9
- @rules = schema_definition[:rules]
10
- end
11
-
12
- def build
13
- fields = @fields
14
- rules = @rules
15
-
16
- Dry::Validation.Contract do
17
- # Define schema based on fields
18
- params do
19
- fields.each do |field|
20
- if field.required?
21
- case field.dry_validation_type
22
- when :integer
23
- required(field.name).value(:integer)
24
- when :float
25
- required(field.name).value(:float)
26
- when :string
27
- required(field.name).value(:string)
28
- when :bool
29
- required(field.name).value(:bool)
30
- when :array
31
- required(field.name).value(:array)
32
- when :hash
33
- required(field.name).value(:hash)
34
- else
35
- required(field.name).filled
36
- end
37
- else
38
- case field.dry_validation_type
39
- when :integer
40
- optional(field.name).maybe(:integer)
41
- when :float
42
- optional(field.name).maybe(:float)
43
- when :string
44
- optional(field.name).maybe(:string)
45
- when :bool
46
- optional(field.name).maybe(:bool)
47
- when :array
48
- optional(field.name).maybe(:array)
49
- when :hash
50
- optional(field.name).maybe(:hash)
51
- else
52
- optional(field.name).value(:any)
53
- end
54
- end
55
- end
56
- end
57
-
58
- # Add custom rules
59
- rules.each do |rule_def|
60
- if rule_def[:name]
61
- # Single key or multiple keys
62
- if rule_def[:name].is_a?(Array)
63
- rule(*rule_def[:name], &rule_def[:block])
64
- else
65
- rule(rule_def[:name], &rule_def[:block])
66
- end
67
- else
68
- # Global rule without a specific field
69
- rule(&rule_def[:block])
70
- end
71
- end
72
-
73
- # Add type validation for custom classes
74
- fields.each do |field|
75
- next unless field.type.is_a?(Class)
76
-
77
- rule(field.name) do
78
- if value && !value.is_a?(field.type)
79
- key.failure("must be an instance of #{field.type}")
80
- end
81
- end
82
- end
83
- end
84
- end
85
- end
86
- end
data/sig/expectant.rbs DELETED
@@ -1,4 +0,0 @@
1
- module Expectant
2
- VERSION: String
3
- # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
- end