rails-surrender 7.0.0 → 8.1.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 (48) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +123 -0
  3. data/LICENSE +674 -0
  4. data/README.md +326 -0
  5. data/lib/rails/surrender/config/locales/en.yml +3 -0
  6. data/lib/rails/surrender/controller_additions.rb +27 -72
  7. data/lib/rails/surrender/fields/asks.rb +50 -0
  8. data/lib/rails/surrender/fields/attribute.rb +34 -0
  9. data/lib/rails/surrender/fields/expand.rb +65 -0
  10. data/lib/rails/surrender/fields/field_tree.rb +71 -0
  11. data/lib/rails/surrender/fields/id_list.rb +38 -0
  12. data/lib/rails/surrender/fields/node.rb +86 -0
  13. data/lib/rails/surrender/menu/endpoint_menu.rb +21 -0
  14. data/lib/rails/surrender/menu/field.rb +20 -0
  15. data/lib/rails/surrender/menu/field_menu.rb +58 -0
  16. data/lib/rails/surrender/menu/filter.rb +16 -0
  17. data/lib/rails/surrender/menu/menu.rb +27 -0
  18. data/lib/rails/surrender/menu/menu_param.rb +28 -0
  19. data/lib/rails/surrender/menu/selection_menu.rb +33 -0
  20. data/lib/rails/surrender/model_additions.rb +47 -32
  21. data/lib/rails/surrender/params/list_param.rb +23 -0
  22. data/lib/rails/surrender/railtie.rb +31 -9
  23. data/lib/rails/surrender/render/resource.rb +11 -30
  24. data/lib/rails/surrender/selection/filtering.rb +144 -0
  25. data/lib/rails/surrender/selection/page_size.rb +37 -0
  26. data/lib/rails/surrender/selection/selected.rb +50 -0
  27. data/lib/rails/surrender/selection/selection.rb +70 -0
  28. data/lib/rails/surrender/selection/sorting.rb +61 -0
  29. data/lib/rails/surrender/version.rb +1 -1
  30. data/lib/rails/surrender.rb +21 -12
  31. metadata +69 -41
  32. data/lib/rails/surrender/config/initializers/active_record_associations_patch.rb +0 -17
  33. data/lib/rails/surrender/config/initializers/active_record_preloader_patch.rb +0 -20
  34. data/lib/rails/surrender/helpers/filter_builder.rb +0 -50
  35. data/lib/rails/surrender/helpers/pagination_builder.rb +0 -25
  36. data/lib/rails/surrender/helpers/query_param_parser.rb +0 -98
  37. data/lib/rails/surrender/helpers/sort_builder.rb +0 -56
  38. data/lib/rails/surrender/model_filter_scopes.rb +0 -56
  39. data/lib/rails/surrender/render/configuration/inclusion_mapper_logic.rb +0 -69
  40. data/lib/rails/surrender/render/configuration/instance_logic.rb +0 -88
  41. data/lib/rails/surrender/render/configuration.rb +0 -93
  42. data/lib/rails/surrender/render/count.rb +0 -21
  43. data/lib/rails/surrender/render/ids.rb +0 -21
  44. data/lib/rails/surrender/render/resource/collection.rb +0 -26
  45. data/lib/rails/surrender/render/resource/inclusion_mapper.rb +0 -48
  46. data/lib/rails/surrender/render/resource/instance.rb +0 -75
  47. data/test/surrender_test.rb +0 -9
  48. data/test/test_helper.rb +0 -21
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../params/list_param'
4
+ require_relative 'node'
5
+
6
+ module Rails
7
+ module Surrender
8
+ # The fields one request renders, nested by expand, worked out from the model and the asks of the request and the
9
+ # controller before any record loads. Preloading and rendering both read it, so they always agree.
10
+ class FieldTree
11
+ # `include:` and `exclude:` are the request's asks, as the query string gives them: `'books:[pages], author'`.
12
+ # A controller's asks are lists: `[:pages, { author: [:name] }]`.
13
+ def initialize(model, include: '', exclude: '', controller_include: [], controller_exclude: [])
14
+ asks = Fields::Asks.new(request_include: Params::ListParam.parse(include, param: :include),
15
+ request_exclude: Params::ListParam.parse(exclude, param: :exclude),
16
+ controller_include: controller_include, controller_exclude: controller_exclude)
17
+ @root = Fields::Node.new(model, asks, [model.base_class])
18
+ end
19
+
20
+ # Renders a record as a hash, or a relation as an array of them.
21
+ def render(resource, ability:)
22
+ records = resource.is_a?(ActiveRecord::Relation) ? resource.to_a : [resource]
23
+ preload(records)
24
+ rendered = records.map { |record| @root.for(record.class).render(record, ability) }
25
+ resource.is_a?(ActiveRecord::Relation) ? rendered : rendered.first
26
+ end
27
+
28
+ def to_h
29
+ @root.to_h
30
+ end
31
+
32
+ private
33
+
34
+ # Level by level, each association loads once for every record that renders it, whatever the record's class.
35
+ # STI subclasses then share a query for an association they inherit, and one only a subclass renders loads only
36
+ # for that subclass's records, which a nested `includes` on the parent's relation can't name.
37
+ def preload(records)
38
+ level = { @root => records }
39
+ until level.empty?
40
+ variants = variants_in(level)
41
+ load_associations(variants)
42
+ level = level_below(variants)
43
+ end
44
+ end
45
+
46
+ def variants_in(level)
47
+ level.flat_map do |node, records|
48
+ records.group_by(&:class).map { |klass, group| [node.for(klass), group] }
49
+ end
50
+ end
51
+
52
+ def load_associations(variants)
53
+ loading = Hash.new { |by_association, association| by_association[association] = [] }
54
+ variants.each { |node, records| node.preloads.each { |association| loading[association].concat(records) } }
55
+ loading.each do |association, records|
56
+ ActiveRecord::Associations::Preloader.new(records: records, associations: association).call
57
+ end
58
+ end
59
+
60
+ def level_below(variants)
61
+ level = Hash.new { |records_by_node, node| records_by_node[node] = [] }
62
+ variants.each do |node, records|
63
+ node.branches.each do |name, branch|
64
+ level[branch].concat(records.flat_map { |record| Array(record.public_send(name)) })
65
+ end
66
+ end
67
+ level.transform_values { |records| records.compact.uniq }.reject { |_, records| records.empty? }
68
+ end
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rails
4
+ module Surrender
5
+ module Fields
6
+ # A field that names an association by its ids, such as chapter_ids, and renders them as a flat list.
7
+ IdList = Data.define(:name, :association) do
8
+ def rank
9
+ 2
10
+ end
11
+
12
+ def type
13
+ :array
14
+ end
15
+
16
+ def preload
17
+ association
18
+ end
19
+
20
+ def circular?(_above)
21
+ false
22
+ end
23
+
24
+ def branch(**); end
25
+
26
+ def menu(**); end
27
+
28
+ def write(record, into:, **)
29
+ into[name] = record.public_send(name)
30
+ end
31
+
32
+ def describe(_branch)
33
+ :id_list
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'asks'
4
+ require_relative 'attribute'
5
+ require_relative 'expand'
6
+ require_relative 'id_list'
7
+
8
+ module Rails
9
+ module Surrender
10
+ module Fields
11
+ # The fields one model renders at one place in the field tree, with a branch below each expand.
12
+ class Node
13
+ attr_reader :branches
14
+
15
+ # `above` holds the base class of every model from the top of the tree down to this one.
16
+ def initialize(model, asks, above)
17
+ @model = model
18
+ @asks = asks
19
+ @above = above
20
+ reject_unavailable_request_includes
21
+ @fields = ordered(rendered_fields)
22
+ @branches = @fields.to_h { |field| [field.name, field.branch(asks: asks, above: above)] }.compact
23
+ @variants = { model => self }
24
+ end
25
+
26
+ # An STI subclass renders its own fields. Its variant is built when one of its records first appears,
27
+ # because subclasses aren't known before they load in development.
28
+ def for(klass)
29
+ @variants[klass] ||= Node.new(klass, @asks, @above)
30
+ end
31
+
32
+ def preloads
33
+ @fields.filter_map(&:preload)
34
+ end
35
+
36
+ def render(record, ability)
37
+ @fields.each_with_object({}) do |field, rendered|
38
+ field.write(record, into: rendered, ability: ability, branch: @branches[field.name])
39
+ end
40
+ end
41
+
42
+ def to_h
43
+ @fields.to_h { |field| [field.name, field.describe(@branches[field.name])] }
44
+ end
45
+
46
+ # Nodes are equal when they render the same fields, so a level loads each association once for all of them.
47
+ def eql?(other)
48
+ other.is_a?(Node) && identity == other.identity
49
+ end
50
+
51
+ alias == eql?
52
+
53
+ def hash
54
+ identity.hash
55
+ end
56
+
57
+ protected
58
+
59
+ def identity
60
+ [@model, @asks, @above]
61
+ end
62
+
63
+ private
64
+
65
+ def reject_unavailable_request_includes
66
+ unavailable = @asks.request_includes.reject { |name| @model.surrenders?(name) }
67
+ return if unavailable.empty?
68
+
69
+ raise Error, I18n.t('surrender.error.query_string.include.not_available', param: unavailable)
70
+ end
71
+
72
+ def rendered_fields
73
+ (@model.surrender_fields + @asks.controller_includes + @asks.request_includes)
74
+ .uniq
75
+ .reject { |name| @asks.excludes?(name) }
76
+ .map { |name| @model.surrender_field(name) }
77
+ .reject { |field| field.circular?(@above) }
78
+ end
79
+
80
+ def ordered(fields)
81
+ fields.each_with_index.sort_by { |field, position| [field.rank, position] }.map(&:first)
82
+ end
83
+ end
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rails
4
+ module Surrender
5
+ # What one endpoint accepts: its model's field menu shaped by the controller's include and exclude, and, for a
6
+ # relation, its selection menu. Rendered instead of the records when a request asks for it.
7
+ class EndpointMenu
8
+ def initialize(resource, include: [], exclude: [], paginate: true)
9
+ model = resource.try(:klass) || (resource.class if resource.is_a?(ActiveRecord::Base))
10
+ @fields = model && FieldMenu.new(model, asks: Fields::Asks.new(controller_include: include,
11
+ controller_exclude: exclude))
12
+ @selection = SelectionMenu.new(model, paginate: paginate) if resource.is_a?(ActiveRecord::Relation)
13
+ end
14
+
15
+ # Nil, hashes and arrays render as given, so no ask applies to them and both parts are null.
16
+ def as_json(*)
17
+ { fields: @fields, selection: @selection }.as_json
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rails
4
+ module Surrender
5
+ class FieldMenu
6
+ # A field a request may ask a model for: the type of what it renders, whether it renders by default, and, for an
7
+ # expand, the field menu of the model it leads to. An attribute's type is its Rails type, or nil for a method the
8
+ # model defines; an id list is an :array, and an expand an :object or, for a collection, an :array.
9
+ Field = Data.define(:name, :type, :default, :menu) do
10
+ def default?
11
+ default
12
+ end
13
+
14
+ def as_json(*)
15
+ { name: name, type: type, default: default }.merge({ fields: menu }.compact).as_json
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'field'
4
+
5
+ module Rails
6
+ module Surrender
7
+ # The fields a request may ask one model for: its default and available fields, nested by expand. It applies
8
+ # wherever the model renders, at the top or inside an expand. A controller's asks shape it as they shape rendering.
9
+ class FieldMenu
10
+ # `above` holds the base class of every model from the top of the menu down to this one.
11
+ def initialize(model, asks: Fields::Asks.new, above: [model.base_class])
12
+ @model = model
13
+ @asks = asks
14
+ @above = above
15
+ end
16
+
17
+ # In the order fields render, with defaults before available fields within each group. Expands back into a model
18
+ # above are left out, as they never render.
19
+ def fields
20
+ @fields ||= offered_fields.map do |field|
21
+ Field.new(name: field.name, type: field.type, default: default?(field.name),
22
+ menu: field.menu(asks: @asks, above: @above))
23
+ end
24
+ end
25
+
26
+ def as_json(*)
27
+ fields.as_json
28
+ end
29
+
30
+ private
31
+
32
+ # A field the controller includes renders by default even when the model doesn't offer it, but a request may
33
+ # only include what the model offers, so a field the controller excludes stays on the menu only if it's offered.
34
+ def offered_fields
35
+ (@model.surrender_fields + @asks.controller_includes + @model.surrender_available_fields)
36
+ .uniq
37
+ .select { |name| on_menu?(name) }
38
+ .map { |name| @model.surrender_field(name) }
39
+ .reject { |field| field.circular?(@above) }
40
+ .each_with_index
41
+ .sort_by { |field, position| [field.rank, default?(field.name) ? 0 : 1, position] }
42
+ .map(&:first)
43
+ end
44
+
45
+ def on_menu?(name)
46
+ default?(name) || @model.surrenders?(name)
47
+ end
48
+
49
+ def default?(name)
50
+ defaults.include?(name)
51
+ end
52
+
53
+ def defaults
54
+ @defaults ||= (@model.surrender_fields + @asks.controller_includes).reject { |name| @asks.excludes?(name) }
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rails
4
+ module Surrender
5
+ class SelectionMenu
6
+ # A filter a request may name, and the column it compares, or nil for a filter the model defines under a name of
7
+ # its own.
8
+ Filter = Data.define(:name, :column) do
9
+ # The column's Rails type tells a client what value to send, such as an ISO 8601 time for a datetime.
10
+ def as_json(*)
11
+ { type: column&.type }.as_json
12
+ end
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'endpoint_menu'
4
+ require_relative 'field_menu'
5
+ require_relative 'menu_param'
6
+ require_relative 'selection_menu'
7
+
8
+ module Rails
9
+ module Surrender
10
+ # Everything a request may ask of one model: its field menu and its selection menu. It is read from the same rules
11
+ # that check requests, so it lists exactly what a request may ask.
12
+ class Menu
13
+ attr_reader :selection
14
+
15
+ delegate :filters, :sorts, :page_size, to: :selection
16
+
17
+ def initialize(model)
18
+ @field_menu = FieldMenu.new(model)
19
+ @selection = SelectionMenu.new(model)
20
+ end
21
+
22
+ def fields
23
+ @field_menu.fields
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rails
4
+ module Surrender
5
+ # The query param a request sends to ask for an endpoint menu, and whether the app answers it. While menus are
6
+ # off the name is not reserved, so an app's own param of that name reaches it as usual.
7
+ MenuParam = Data.define(:enabled, :name) do
8
+ def initialize(enabled: false, name: 'menu')
9
+ name = name.to_s
10
+ raise ArgumentError, 'menu_param needs a name' if name.empty?
11
+ raise ArgumentError, "menu_param can't be #{name.inspect}, which surrender already reads" if reserved?(name)
12
+
13
+ super
14
+ end
15
+
16
+ def asked_in?(query_params)
17
+ enabled && query_params.key?(name.to_sym)
18
+ end
19
+
20
+ private
21
+
22
+ # A menu named after a param surrender already reads would hide it.
23
+ def reserved?(name)
24
+ %w[include exclude filter sort page per count].include?(name)
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'filter'
4
+
5
+ module Rails
6
+ module Surrender
7
+ # The filters, sorts and page size a request may use to pick a model's records. They apply only at the top of a
8
+ # response, to a relation; nothing filters or sorts the records inside an expand.
9
+ class SelectionMenu
10
+ def initialize(model, paginate: true)
11
+ @model = model
12
+ @paginate = paginate
13
+ end
14
+
15
+ def filters
16
+ @model.surrender_filter_columns.map { |name, column| Filter.new(name: name, column: column) }
17
+ end
18
+
19
+ def sorts
20
+ @model.surrender_sort_names
21
+ end
22
+
23
+ # Nil when the controller skips pagination, as its records then come in one piece.
24
+ def page_size
25
+ Surrender.page_size if @paginate
26
+ end
27
+
28
+ def as_json(*)
29
+ { filters: filters.to_h { |filter| [filter.name, filter] }, sorts: sorts, page: page_size }.as_json
30
+ end
31
+ end
32
+ end
33
+ end
@@ -2,56 +2,71 @@
2
2
 
3
3
  module Rails
4
4
  module Surrender
5
- # Aad methods to the model class to describe how the model renders.
5
+ # Adds methods to the model class to describe how the model renders.
6
6
  module ModelAdditions
7
7
  def self.included(base)
8
- attr_accessor :surrender_attributes
9
- attr_accessor :surrender_expands
10
- attr_accessor :surrender_available_attributes
11
- attr_accessor :surrender_available_expands
12
-
13
8
  base.extend(ClassMethods)
14
9
  end
15
10
 
11
+ # A model lists the fields it renders by default, and those a request may add with `include`. Fields that name
12
+ # an association expand into the associated resource; every other field is rendered as an attribute.
16
13
  module ClassMethods
17
- def surrenders(*args)
18
- directives = args.extract_options!
19
-
20
- # Run through the various lists of attributes and assign them to the rendering context
21
- # If the superclass has attributes then consume those as well.
22
- %w[attributes expands available_attributes available_expands].each do |directive|
23
- surrender_directive = "surrender_#{directive}"
24
- list = []
25
- if superclass.instance_variable_defined?("@#{surrender_directive}")
26
- list << superclass.instance_variable_get("@#{surrender_directive}")
27
- end
28
- list << directives[directive.to_sym] if directives.key?(directive.to_sym)
29
- instance_variable_set("@#{surrender_directive}", list.flatten.uniq)
30
- end
14
+ DEFAULT_FIELDS = %i[id created_at].freeze
15
+
16
+ # Fields are sorted into attributes and associations when read, not here, because models often call
17
+ # `surrenders` before declaring the associations it names.
18
+ def surrenders(*fields, available: [])
19
+ @surrender_fields = (inherited_surrender(:@surrender_fields) + fields.map(&:to_sym)).uniq
20
+ @surrender_available_fields =
21
+ (inherited_surrender(:@surrender_available_fields) + Array(available).map(&:to_sym)).uniq
22
+ end
23
+
24
+ def surrender_fields
25
+ @surrender_fields || DEFAULT_FIELDS
31
26
  end
32
27
 
33
- def surrender_attributes
34
- @surrender_attributes ||= %i[id created_at]
28
+ def surrender_available_fields
29
+ @surrender_available_fields || []
35
30
  end
36
31
 
37
- def surrender_available_attributes
38
- @surrender_available_attributes ||= []
32
+ # Everything a request may ask of the model: its field menu and its selection menu.
33
+ def surrender_menu
34
+ Menu.new(self)
39
35
  end
40
36
 
41
- def surrender_expands
42
- @surrender_expands ||= []
37
+ # Whether a request may include the field: it renders by default or is available.
38
+ def surrenders?(name)
39
+ surrender_callable_fields.include?(name.to_sym)
43
40
  end
44
41
 
45
- def surrender_available_expands
46
- @surrender_available_expands ||= []
42
+ # An association expands, a *_ids name of an association is an id list, and anything else is an attribute.
43
+ def surrender_field(name)
44
+ name = name.to_sym
45
+ if (reflection = reflect_on_association(name))
46
+ Fields::Expand.new(name: name, reflection: reflection)
47
+ elsif (association = id_list_association(name))
48
+ Fields::IdList.new(name: name, association: association)
49
+ else
50
+ Fields::Attribute.new(name: name, type: type_for_attribute(name).type)
51
+ end
52
+ end
53
+
54
+ private
55
+
56
+ def id_list_association(name)
57
+ return unless name.end_with?('_ids')
58
+
59
+ association = name.to_s.delete_suffix('_ids').pluralize.to_sym
60
+ association if reflect_on_association(association)
47
61
  end
48
62
 
49
- def surrender_callable_attributes
50
- @surrender_callable_attributes ||= (surrender_attributes + surrender_available_attributes).flatten
63
+ # A subclass may make a default of a field its superclass only made available.
64
+ def surrender_callable_fields
65
+ (surrender_fields + surrender_available_fields).uniq
51
66
  end
52
67
 
53
- def surrender_callable_expands
54
- @surrender_callable_expands ||= (surrender_expands + surrender_available_expands).flatten
68
+ def inherited_surrender(variable)
69
+ superclass.instance_variable_defined?(variable) ? superclass.instance_variable_get(variable) : []
55
70
  end
56
71
  end
57
72
  end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rails
4
+ module Surrender
5
+ module Params
6
+ # A query param that lists names, names with values, and nested lists, such as `genre:fantasy, author:[name]`.
7
+ # It is read as the YAML of a flow sequence, so values come back typed: `long:true` holds true, not 'true'.
8
+ class ListParam
9
+ # YAML needs a space after each comma and colon that separates entries, but not inside quoted values, where it
10
+ # would change the value: '13:30' must stay '13:30'.
11
+ SEPARATORS_OUTSIDE_QUOTES = /'[^']*'|"[^"]*"|[,:]/
12
+
13
+ # `param` names the query param in the error a malformed value raises.
14
+ def self.parse(text, param:)
15
+ spaced = text.to_s.gsub(SEPARATORS_OUTSIDE_QUOTES) { |match| match.length == 1 ? "#{match} " : match }
16
+ Psych.safe_load("[#{spaced}]")
17
+ rescue Psych::Exception
18
+ raise Error, I18n.t('surrender.error.query_string.incorrect_format', param: param)
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
@@ -2,19 +2,41 @@
2
2
 
3
3
  module Rails
4
4
  module Surrender
5
+ # Hooks surrender into Rails as each framework loads. Using load hooks rather than after_initialize matters
6
+ # in eager loaded environments, where models call `surrenders` before after_initialize runs.
5
7
  class Railtie < ::Rails::Railtie
6
- config.after_initialize do
7
- ActionController::Base.class_eval do
8
- include Rails::Surrender::ControllerAdditions
9
- end
8
+ config.surrender = ActiveSupport::OrderedOptions.new
9
+ config.surrender.default_per_page = 50
10
+ config.surrender.max_per_page = 100
11
+ config.surrender.menus = false
12
+ config.surrender.menu_param = 'menu'
10
13
 
11
- ActionController::API.class_eval do
12
- include Rails::Surrender::ControllerAdditions
13
- end
14
+ # Built once at boot, so a page size setting that makes no sense stops the app from starting.
15
+ initializer 'rails_surrender.page_size' do |app|
16
+ Rails::Surrender.page_size = Rails::Surrender::Selection::PageSize.new(
17
+ default: app.config.surrender.default_per_page, max: app.config.surrender.max_per_page
18
+ )
19
+ end
20
+
21
+ initializer 'rails_surrender.menu_param' do |app|
22
+ Rails::Surrender.menu_param = Rails::Surrender::MenuParam.new(
23
+ enabled: app.config.surrender.menus, name: app.config.surrender.menu_param
24
+ )
25
+ end
26
+
27
+ initializer 'rails_surrender.locales' do |app|
28
+ app.config.i18n.load_path += Dir[File.expand_path('config/locales/*.yml', __dir__)]
29
+ end
30
+
31
+ initializer 'rails_surrender.action_controller' do
32
+ ActiveSupport.on_load(:action_controller) { include Rails::Surrender::ControllerAdditions }
33
+ end
14
34
 
15
- ActiveRecord::Base.class_eval do
35
+ initializer 'rails_surrender.active_record' do
36
+ ActiveSupport.on_load(:active_record) do
16
37
  include Rails::Surrender::ModelAdditions
17
- include Rails::Surrender::ModelFilterScopes
38
+ include Rails::Surrender::Selection::Filtering
39
+ include Rails::Surrender::Selection::Sorting
18
40
  end
19
41
  end
20
42
  end
@@ -1,52 +1,33 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative 'resource/inclusion_mapper'
4
- require_relative 'resource/collection'
5
- require_relative 'resource/instance'
6
-
7
3
  module Rails
8
4
  module Surrender
9
5
  module Render
10
- # Rendering a resource, and it's various nested components, according to the given config params.
6
+ # Renders what a controller surrenders. Records and relations render through a field tree; nil, hashes and
7
+ # arrays have no model to shape them, so they render as given.
11
8
  class Resource
12
- attr_reader :resource, :ability, :config
9
+ attr_reader :resource, :ability, :asks
13
10
 
14
- def initialize(resource:, ability:, config:)
11
+ # `asks` holds the keyword arguments of FieldTree.new other than the model.
12
+ def initialize(resource:, ability:, asks: {})
15
13
  @resource = resource
16
14
  @ability = ability
17
- @config = config
15
+ @asks = asks
18
16
  end
19
17
 
20
18
  def parse
21
19
  data = case resource
22
- when nil? then {}
23
- when Hash || Array then resource
24
- when ActiveRecord::Relation then collection_data
25
- else instance_data
20
+ when nil then {}
21
+ when Hash, Array then resource
22
+ else FieldTree.new(model, **asks).render(resource, ability: ability)
26
23
  end
27
24
  Response.new(data: data)
28
25
  end
29
26
 
30
27
  private
31
28
 
32
- def collection_data
33
- includes = InclusionMapper.new(resource_class: resource.klass, config: config).parse
34
- data = @resource.includes(includes)
35
- Collection.new(resource: data, config: config, ability: ability).render
36
- end
37
-
38
- def instance_data
39
- # Reloading the instance here allows us to take advantage of the eager loading
40
- # capabilities of ActiveRecord with our 'includes' hash to prevent N+1 queries.
41
- # This can save a TON of response time when the data sets begin to get large.
42
- data = if config.reload_resource?
43
- includes = InclusionMapper.new(resource_class: resource.class, config: config).parse
44
- @resource = resource.class.includes(includes).find_by_id(resource.id)
45
- else
46
- resource
47
- end
48
-
49
- Instance.new(resource: data, config: config, ability: ability).render
29
+ def model
30
+ resource.try(:klass) || resource.class
50
31
  end
51
32
  end
52
33
  end