nueca_rails_interfaces 1.1.2 → 1.2.9

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: dbcdb703d90c83096aa868e52808ce08c4801267cca85927ae1299cf70f0ed32
4
- data.tar.gz: ea0af8ccfca4f1561382d5e25ee97ff4ca4b95d5702d4ad5957bf80ab80284b4
3
+ metadata.gz: 06fa9d84241065bed1906ea3c75590d9d3651ad508e4994653e5edfc7f7f9b60
4
+ data.tar.gz: 1a08ad66325e0db8c57f2601115bee93d00490b4f59d4aaf0226c7a06cebdc39
5
5
  SHA512:
6
- metadata.gz: 66f4e97c4d687815f825d0fc4c22d529f716846b4f845415b0f5f35784140cef97cd159b30617e009484f84b9c3ddec80bbdc8e1b8e502ee82eae1e52d49a5e8
7
- data.tar.gz: 859e241733b214d7c168f0ab0a020e906eab24179a60d78bf777146cb30f617b62c247f710797a45936528c8795731a453091d62c69d2d049933dd1fbba76fed
6
+ metadata.gz: cc1c35a7af8f4e6e871ff6d0445f27fc4405faae4f8e2ed9fd6b1c51652b6688c2d708e63a8ae4697d4ed500a2ba40086307a81150953e7f3c2a9eef73e3355a
7
+ data.tar.gz: ac34f696efc3b533c3bbb0c5d19aa1806b18c457f80fb28e8908f07631a8d02d28ff145d444ed960a63ba8f3d033cccf4f125ab94a01fd0eefa7c035caf3ea9d
data/.rubocop.yml CHANGED
@@ -1,17 +1,9 @@
1
1
  plugins:
2
- - rubocop-rails
2
+ - rubocop-nueca
3
3
  - rubocop-rake
4
- - rubocop-rspec
5
4
 
6
- AllCops:
7
- TargetRubyVersion: 3.3
8
- NewCops: enable
9
-
10
- Layout/LineLength:
11
- Max: 120
12
-
13
- RSpec/NestedGroups:
14
- Max: 5
5
+ Style/ClassMethodsDefinitions:
6
+ Enabled: false
15
7
 
16
- RSpec/VerifiedDoubles:
8
+ Style/OptionHash:
17
9
  Enabled: false
data/Rakefile CHANGED
@@ -9,4 +9,4 @@ require 'rubocop/rake_task'
9
9
 
10
10
  RuboCop::RakeTask.new
11
11
 
12
- task default: %i[spec rubocop]
12
+ task default: [:spec, :rubocop]
@@ -86,7 +86,7 @@ module NuecaRailsInterfaces
86
86
 
87
87
  # Paginates the collection based on query or settings.
88
88
  def apply_pagination!
89
- raise 'Invalid pagination settings.' unless correct_pagination_settings?
89
+ raise 'Invalid pagination settings.' unless correct_pagination_settings? # rubocop:disable Style/ImplicitRuntimeError
90
90
  return unless @pagination_flag
91
91
 
92
92
  @collection = collection.paginate(page: fetch_page_value, per_page: fetch_per_page_value)
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module NuecaRailsInterfaces
4
+ module V2
5
+ module Pagination
6
+ # Base adapter module for pagination strategies
7
+ # Modules must implement the .paginate(collection, page, per_page) method
8
+ module BaseAdapter
9
+ # Paginate the collection based on the provided page and per page values.
10
+ # @param [ActiveRecord::Relation] collection The collection to be paginated.
11
+ # @param [Integer] page The page number.
12
+ # @param [Integer] per_page The number of records per page.
13
+ # @return [ActiveRecord::Relation] The paginated collection.
14
+ def paginate(collection, page, per_page)
15
+ raise NotImplementedError, "#{name} must implement the .paginate(collection, page, per_page) method"
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'base_adapter'
4
+
5
+ module NuecaRailsInterfaces
6
+ module V2
7
+ module Pagination
8
+ # Adapter for Kaminari gem.
9
+ module KaminariAdapter
10
+ extend BaseAdapter
11
+
12
+ def self.paginate(collection, page, per_page)
13
+ collection.page(page).per(per_page)
14
+ end
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'base_adapter'
4
+
5
+ module NuecaRailsInterfaces
6
+ module V2
7
+ module Pagination
8
+ # Adapter for Pagy gem.
9
+ module PagyAdapter
10
+ extend BaseAdapter
11
+
12
+ def self.paginate(collection, page, per_page)
13
+ @helper ||= Class.new { include ::Pagy::Backend }.new
14
+ _pagy, records = @helper.send(:pagy, collection, page: page, items: per_page)
15
+ records
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'base_adapter'
4
+
5
+ module NuecaRailsInterfaces
6
+ module V2
7
+ module Pagination
8
+ # Adapter for WillPaginate gem.
9
+ module WillPaginateAdapter
10
+ extend BaseAdapter
11
+
12
+ def self.paginate(collection, page, per_page)
13
+ collection.paginate(page: page, per_page: per_page)
14
+ end
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,162 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'pagination/base_adapter'
4
+ require_relative 'pagination/will_paginate_adapter'
5
+ require_relative 'pagination/kaminari_adapter'
6
+ require_relative 'pagination/pagy_adapter'
7
+
8
+ module NuecaRailsInterfaces
9
+ module V2
10
+ # V2 Query Interface is the same as V1 Query Interface,
11
+ # but with changes in the pagination logic.
12
+ # V1 had tight coupling with WillPaginate, this version decouples the query interface from it,
13
+ # allowing for custom pagination adapters to be used.
14
+ module QueryInterface
15
+ # The basis for validity of pagination settings. It also contains default values.
16
+ VALID_PAGINATION_HASH = {
17
+ max: 20, # Absolute maximum number of records per page, even if the query requests for more.
18
+ min: 1, # Absolute minimum number of records per page, even if the query requests for less.
19
+ per_page: 20, # Default number of records per page if not specified in the query.
20
+ page: 1 # Default page number if not specified in the query.
21
+ }.freeze
22
+
23
+ # Basis for considering a non-paging result even when the query is being processed for pagination.
24
+ # This number states the invalidity of pagination, but it exists for legacy support.
25
+ NO_PAGING_THRESHOLD = 1_000_000
26
+
27
+ class << self
28
+ def included(base)
29
+ # This is the method to call outside this object to apply the query filters, sortings and paginations.
30
+ # @param [Hash] query The query parameters.
31
+ # @param [ActiveRecord::Relation] collection The collection to be queried.
32
+ base.define_singleton_method(:call) do |query, collection|
33
+ new(query, collection).call
34
+ end
35
+ end
36
+ end
37
+
38
+ attr_reader :query, :collection
39
+
40
+ # Do not override! This is how we will always initialize our query objects.
41
+ # No processing should be done in the initialize method.
42
+ # @param [Hash] query The query parameters.
43
+ # @param [ActiveRecord::Relation] collection The collection to be queried.
44
+ def initialize(query, collection, pagination: true)
45
+ @query = query
46
+ @collection = collection
47
+ @pagination_flag = pagination
48
+ query_aliases
49
+ end
50
+
51
+ # Do not override. This is the method to call outside this object
52
+ # to apply the query filters, sortings and paginations.
53
+ def call
54
+ apply_filters!
55
+ apply_sorting!
56
+ apply_pagination!
57
+ collection
58
+ end
59
+
60
+ private
61
+
62
+ # Place here filters. Be sure to assign @collection to override the original collection. Be sure it is private!
63
+ def filters; end
64
+
65
+ # Place here sorting logic. Be sure to assign @collection to override the original collection.
66
+ # Be sure it is private!
67
+ def sorts; end
68
+
69
+ # Pagination settings to modify the default behavior of a query object.
70
+ # Default values are in VALID_PAGINATION_HASH constant.
71
+ # Override the method to change the default values.
72
+ def pagination_settings
73
+ {}
74
+ end
75
+
76
+ # Always updated alias of filters.
77
+ def apply_filters!
78
+ filters
79
+ end
80
+
81
+ # Always updated alias of sorts.
82
+ def apply_sorting!
83
+ sorts
84
+ end
85
+
86
+ # Paginates the collection based on query or settings.
87
+ def apply_pagination!
88
+ raise 'Invalid pagination settings.' unless correct_pagination_settings? # rubocop:disable Style/ImplicitRuntimeError
89
+ return unless @pagination_flag
90
+
91
+ @collection = pagination_adapter.paginate(collection, fetch_page_value, fetch_per_page_value)
92
+ end
93
+
94
+ # Selects the appropriate pagination adapter based on loaded gems.
95
+ # The first adapter found will be used.
96
+ # The adapters are checked in the following order: WillPaginate, Kaminari, Pagy.
97
+ # Override this method if using custom pagination adapter.
98
+ # @return [NuecaRailsInterfaces::V2::Pagination::BaseAdapter] The pagination adapter.
99
+ def pagination_adapter
100
+ @pagination_adapter ||=
101
+ if defined?(::WillPaginate)
102
+ NuecaRailsInterfaces::V2::Pagination::WillPaginateAdapter
103
+ elsif defined?(::Kaminari)
104
+ NuecaRailsInterfaces::V2::Pagination::KaminariAdapter
105
+ elsif defined?(::Pagy)
106
+ NuecaRailsInterfaces::V2::Pagination::PagyAdapter
107
+ else
108
+ # rubocop:disable Style/ImplicitRuntimeError
109
+ raise 'No compatible pagination library detected (WillPaginate, Kaminari, or Pagy) ' \
110
+ 'and collection does not respond to :paginate.'
111
+ # rubocop:enable Style/ImplicitRuntimeError
112
+ end
113
+ end
114
+
115
+ # Logic for fetching the page value from the query or settings.
116
+ def fetch_page_value
117
+ query&.key?(:page) ? query[:page].to_i : merged_pagination_settings[:page]
118
+ end
119
+
120
+ # Logic for fetching the per page value from the query or settings.
121
+ def fetch_per_page_value
122
+ per_page = query&.key?(:per_page) ? query[:per_page].to_i : merged_pagination_settings[:per_page]
123
+ per_page.clamp(merged_pagination_settings[:min], merged_pagination_settings[:max])
124
+ end
125
+
126
+ # Checks if the pagination settings are correct.
127
+ # The app crashes on misconfiguration.
128
+ def correct_pagination_settings?
129
+ return false unless pagination_settings.is_a?(Hash)
130
+
131
+ detected_keys = []
132
+ merged_pagination_settings.each_key do |key|
133
+ return false unless VALID_PAGINATION_HASH.key?(key)
134
+
135
+ detected_keys << key
136
+ end
137
+
138
+ detected_keys.sort == VALID_PAGINATION_HASH.keys.sort
139
+ end
140
+
141
+ # The final result of pagination settings, and thus the used one.
142
+ def merged_pagination_settings
143
+ @merged_pagination_settings ||= VALID_PAGINATION_HASH.merge(pagination_settings)
144
+ end
145
+
146
+ # Aliases for query parameters for legacy support.
147
+ # No need to override this in children. Directly modify this method in this interface if need be.
148
+ def query_aliases
149
+ query[:per_page] = query[:limit] if query[:limit].present? && query[:per_page].blank?
150
+ end
151
+
152
+ # For deprecation. Use this for queries that do not need pagination.
153
+ # Queries will still be paginated as a result, but with the use of the threshold,
154
+ # the result is as good as a non-paginated result,
155
+ # and it will be treated as such.
156
+ def no_pagination
157
+ Rails.logger.warn 'Querying without paging is deprecated. Enforce paging in queries!'
158
+ { max: NO_PAGING_THRESHOLD, min: NO_PAGING_THRESHOLD }
159
+ end
160
+ end
161
+ end
162
+ end
@@ -0,0 +1,166 @@
1
+ # frozen_string_literal: true
2
+
3
+ module NuecaRailsInterfaces
4
+ module V3
5
+ # V3 Form Interface delegates model validation to the actual model instances
6
+ # rather than reimplementing model validations inside the form.
7
+ #
8
+ # Models managed by the form are declared explicitly with the `model` macro.
9
+ # Their attributes arrive as a nested hash keyed by the model name, which is
10
+ # what `fields_for :school_year, f.object.school_year` produces in the view;
11
+ # e.g. `school_year: { name: "..." }`. This maps directly to:
12
+ # `params.expect(my_form: [{ school_year: [:name] }, :other_field])`
13
+ #
14
+ # Only models listed in the `model` macro are processed; any key whose name
15
+ # matches a declared model and whose value is a Hash (or Parameters) is treated
16
+ # as model attributes. Everything else is treated as a regular form attribute.
17
+ # Fields inside a model hash that the model does not recognise are silently
18
+ # discarded.
19
+ #
20
+ # Custom form-level fields (fields that belong to the form, not to any model)
21
+ # are declared as plain `attr_accessor`s on the form class, just like any other
22
+ # ActiveModel attribute.
23
+ #
24
+ # Calling `valid?` on the form runs form-level validations first, then calls
25
+ # `valid?` on each model instance and propagates any model errors onto the form
26
+ # under the model name key (e.g. `errors[:payment]`). `fields_for :payment`
27
+ # in the view binds to `form.payment` and reads that object's own errors for
28
+ # per-field error rendering, so both levels work naturally together.
29
+ #
30
+ # The `attributes` method returns a hash of model instances merged with any
31
+ # regular form attributes. It can be overridden in the form class.
32
+ module FormInterface
33
+ # Prepended so these methods precede ActiveModel::Model's versions in the
34
+ # method resolution order. When `base.include(ActiveModel::Model)` is called
35
+ # inside the `included` hook, ActiveModel ends up earlier in the ancestor chain,
36
+ # which would otherwise cause ActiveModel::API#initialize to intercept `new`
37
+ # before our param-splitting logic runs.
38
+ module InstanceMethods
39
+ def initialize(options = {})
40
+ @model_instances = {}
41
+ @regular_attributes = extract_regular_attributes(options)
42
+
43
+ # Pre-instantiate declared models that were not present in the params
44
+ # (e.g. the form is used in a `new` action with no input yet).
45
+ (self.class.declared_models - @model_instances.keys).each do |model_sym|
46
+ @model_instances[model_sym] = model_sym.to_s.camelize.constantize.new
47
+ end
48
+
49
+ super(**@regular_attributes)
50
+ end
51
+
52
+ def valid?(context = nil)
53
+ # Clears errors and runs form-level validations.
54
+ super
55
+
56
+ error_key = self.class.flatten_errors? ? :base : nil
57
+
58
+ @model_instances.each do |model_name, model_instance|
59
+ next if model_instance.valid?
60
+
61
+ model_instance.errors.each do |error|
62
+ errors.add(error_key || model_name, error.full_message)
63
+ end
64
+ end
65
+
66
+ errors.empty?
67
+ end
68
+
69
+ def method_missing(name, *args, &)
70
+ return @model_instances[name] if @model_instances.key?(name)
71
+
72
+ super
73
+ end
74
+
75
+ def respond_to_missing?(name, include_private = false)
76
+ @model_instances.key?(name) || super
77
+ end
78
+
79
+ private
80
+
81
+ # Builds the model instance from the given attributes hash, assigning only
82
+ # fields the model recognises. Unknown fields are silently discarded.
83
+ # `attrs` may be a plain Hash or ActionController::Parameters; both are
84
+ # normalised to a plain Hash before processing; field whitelisting via
85
+ # Splits options into model instances and regular form attributes.
86
+ # Hash-valued keys matching a declared model are built into model instances.
87
+ # Hash-valued keys for undeclared models are silently discarded.
88
+ # All other (scalar) keys are returned as regular attributes for super.
89
+ def extract_regular_attributes(options)
90
+ regular_attrs = {}
91
+ options.each do |key, value|
92
+ if self.class.declared_models.include?(key.to_sym) && value.respond_to?(:each_pair)
93
+ build_model_instance(key.to_sym, value)
94
+ elsif !value.respond_to?(:each_pair)
95
+ regular_attrs[key] = value
96
+ end
97
+ end
98
+ regular_attrs
99
+ end
100
+
101
+ # `model_field?` provides the equivalent of strong-param filtering here.
102
+ def build_model_instance(model_name, attrs)
103
+ model_class = model_name.to_s.camelize.constantize
104
+ attrs_hash = attrs.respond_to?(:to_unsafe_h) ? attrs.to_unsafe_h : attrs.to_h
105
+ model_attrs = attrs_hash.each_with_object({}) do |(field, value), hash|
106
+ hash[field.to_sym] = value if model_field?(model_class, field.to_s)
107
+ end
108
+ @model_instances[model_name] = model_class.new(**model_attrs)
109
+ end
110
+
111
+ # A field belongs to the model if the model class declares it via
112
+ # `attribute_names` (ActiveRecord) or has an assignment method
113
+ # (ActiveModel attr_accessor, etc.).
114
+ def model_field?(model_class, field_name)
115
+ (model_class.respond_to?(:attribute_names) && model_class.attribute_names.include?(field_name)) ||
116
+ model_class.method_defined?("#{field_name}=")
117
+ end
118
+ end
119
+
120
+ class << self
121
+ def included(base)
122
+ base.include(ActiveModel::Model)
123
+ base.prepend(InstanceMethods)
124
+ define_class_macros(base)
125
+ end
126
+
127
+ private
128
+
129
+ def define_class_macros(base)
130
+ base.instance_variable_set(:@declared_models, [])
131
+ base.instance_variable_set(:@flatten_errors, false)
132
+
133
+ base.define_singleton_method(:flatten_errors) { @flatten_errors = true }
134
+ base.define_singleton_method(:flatten_errors?) { @flatten_errors }
135
+
136
+ # Declares one or more models managed by this form. Each symbol must be
137
+ # the underscored model name (e.g. `model :payment`, `model :school_year`).
138
+ # Only declared models are processed from params. Declared models are always instantiated
139
+ # (with blank attributes) even when their params are absent.
140
+ base.define_singleton_method(:model) do |*model_names|
141
+ model_names.each { |n| @declared_models << n.to_sym }
142
+ end
143
+
144
+ base.define_singleton_method(:declared_models) { @declared_models }
145
+
146
+ base.define_singleton_method(:check) do |*arguments|
147
+ instance = NuecaRailsInterfaces::Util.process_class_arguments(self, *arguments)
148
+ instance.valid?
149
+ instance
150
+ end
151
+ end
152
+ end
153
+
154
+ # Returns a merged hash of model instances and regular form attributes.
155
+ # Defined here (included, not prepended) so that a form class can override it
156
+ # by defining its own `attributes` method; the class-level definition is found
157
+ # first in the MRO, falling back to this default when no override exists.
158
+ def attributes
159
+ result = {}
160
+ result.merge!(@model_instances)
161
+ result.merge!(@regular_attributes.transform_keys(&:to_sym))
162
+ result.with_indifferent_access
163
+ end
164
+ end
165
+ end
166
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module NuecaRailsInterfaces
4
- VERSION = '1.1.2'
4
+ VERSION = '1.2.9'
5
5
  end
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- raise 'Rails not found' unless defined?(Rails)
3
+ raise 'Rails not found' unless defined?(Rails) # rubocop:disable Style/ImplicitRuntimeError
4
4
 
5
5
  require 'to_bool'
6
6
 
@@ -16,7 +16,7 @@ Gem::Specification.new do |spec|
16
16
  spec.files = Dir.chdir(__dir__) do
17
17
  `git ls-files -z`.split("\x0").reject do |f|
18
18
  (File.expand_path(f) == __FILE__) ||
19
- f.start_with?(*%w[bin/ test/ spec/ features/ .git .gitlab-ci.yml appveyor Gemfile])
19
+ f.start_with?('bin/', 'test/', 'spec/', 'features/', '.git', '.gitlab-ci.yml', 'appveyor', 'Gemfile')
20
20
  end
21
21
  end
22
22
  spec.bindir = 'exe'
metadata CHANGED
@@ -1,13 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: nueca_rails_interfaces
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.1.2
4
+ version: 1.2.9
5
5
  platform: ruby
6
6
  authors:
7
7
  - Tien
8
+ autorequire:
8
9
  bindir: exe
9
10
  cert_chain: []
10
- date: 1980-01-02 00:00:00.000000000 Z
11
+ date: 2026-06-24 00:00:00.000000000 Z
11
12
  dependencies:
12
13
  - !ruby/object:Gem::Dependency
13
14
  name: rails
@@ -43,6 +44,7 @@ dependencies:
43
44
  - - "~>"
44
45
  - !ruby/object:Gem::Version
45
46
  version: '2.1'
47
+ description:
46
48
  email:
47
49
  - tieeeeen1994@gmail.com
48
50
  executables: []
@@ -63,7 +65,13 @@ files:
63
65
  - lib/nueca_rails_interfaces/v1/query_interface.rb
64
66
  - lib/nueca_rails_interfaces/v1/service_interface.rb
65
67
  - lib/nueca_rails_interfaces/v2/form_interface.rb
68
+ - lib/nueca_rails_interfaces/v2/pagination/base_adapter.rb
69
+ - lib/nueca_rails_interfaces/v2/pagination/kaminari_adapter.rb
70
+ - lib/nueca_rails_interfaces/v2/pagination/pagy_adapter.rb
71
+ - lib/nueca_rails_interfaces/v2/pagination/will_paginate_adapter.rb
72
+ - lib/nueca_rails_interfaces/v2/query_interface.rb
66
73
  - lib/nueca_rails_interfaces/v2/service_interface.rb
74
+ - lib/nueca_rails_interfaces/v3/form_interface.rb
67
75
  - lib/nueca_rails_interfaces/v3/service_interface.rb
68
76
  - lib/nueca_rails_interfaces/version.rb
69
77
  - nueca_rails_interfaces.gemspec
@@ -72,6 +80,7 @@ licenses:
72
80
  - MIT
73
81
  metadata:
74
82
  rubygems_mfa_required: 'true'
83
+ post_install_message:
75
84
  rdoc_options: []
76
85
  require_paths:
77
86
  - lib
@@ -86,7 +95,8 @@ required_rubygems_version: !ruby/object:Gem::Requirement
86
95
  - !ruby/object:Gem::Version
87
96
  version: '0'
88
97
  requirements: []
89
- rubygems_version: 3.7.1
98
+ rubygems_version: 3.0.3.1
99
+ signing_key:
90
100
  specification_version: 4
91
101
  summary: Interfaces for known object entities in Rails Development at Nueca.
92
102
  test_files: []