|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module Blueprinter |
| 4 | + # @api private |
| 5 | + # |
| 6 | + # Compiles a view into a module whose `call(object, options)` builds the object's Hash with a Hash literal and direct |
| 7 | + # method calls, e.g. `{ id: object.id, name: object.name }`. Used when `Blueprinter.configuration.compile_views` is on. |
| 8 | + # |
| 9 | + # Only simple fields are compiled: values read with AutoExtractor (by method or block), optionally with if/unless and |
| 10 | + # exclude_if_nil. Every other field (associations, defaults, datetime formats, custom extractors) calls Field#skip? and |
| 11 | + # Field#extract, exactly like standard rendering. |
| 12 | + # |
| 13 | + # The result is only valid while datetime_format, field_default and the global if/unless are unset; |
| 14 | + # Rendering#prepare_data checks that on every render. Blocks, callables, fields, transformers and unusual names live in |
| 15 | + # the module's REFS constant and are referenced by index, so user-provided text is never interpolated as code. |
| 16 | + module ViewCompiler |
| 17 | + # Method names that can be called directly as `object.name` |
| 18 | + CALLABLE_METHOD = /\A[a-z_][a-zA-Z0-9_]*[?!]?\z/ |
| 19 | + # Symbols that can be written as `name:` keys or `:name` literals |
| 20 | + LITERAL_SYMBOL = /\A[a-zA-Z_][a-zA-Z0-9_]*\z/ |
| 21 | + |
| 22 | + module_function |
| 23 | + |
| 24 | + # @return [Module] responds to `call(object, options)` and returns the object's Hash |
| 25 | + def compile(fields, transformers) |
| 26 | + refs = [] |
| 27 | + ref = ->(value) { "REFS[#{refs.push(value).size - 1}]" } |
| 28 | + body = body(fields, transformers, ref) |
| 29 | + |
| 30 | + Module.new.tap do |compiled| |
| 31 | + compiled.const_set(:REFS, refs.freeze) |
| 32 | + compiled.module_eval(<<~RUBY, __FILE__, __LINE__ + 1) |
| 33 | + def self.call(object, options) # def self.call(object, options) |
| 34 | + #{body} # { id: object.id, name: object.name } |
| 35 | + end # end |
| 36 | + RUBY |
| 37 | + end |
| 38 | + end |
| 39 | + |
| 40 | + def body(fields, transformers, ref) |
| 41 | + literal = [] |
| 42 | + statements = [] |
| 43 | + keys = {} |
| 44 | + |
| 45 | + fields.each do |field| |
| 46 | + key = key_for(field.name, ref) |
| 47 | + value = simple_value(field, ref) |
| 48 | + # A repeated name keeps its first position and its last value, like assigning a Hash key twice |
| 49 | + if value && statements.empty? && literal_field?(field, keys) |
| 50 | + literal << "#{key} => #{value}" |
| 51 | + else |
| 52 | + statements << statement(field, key, value, ref) |
| 53 | + end |
| 54 | + keys[field.name] = true |
| 55 | + end |
| 56 | + transformers.each { |transformer| statements << "#{ref.call(transformer)}.transform(h, object, options)" } |
| 57 | + |
| 58 | + statements.empty? ? "{ #{literal.join(', ')} }" : "h = { #{literal.join(', ')} }\n#{statements.join("\n")}\nh" |
| 59 | + end |
| 60 | + |
| 61 | + # The value expression for a field compiled directly, or nil for a field that uses standard rendering |
| 62 | + def simple_value(field, ref) |
| 63 | + options = field.options |
| 64 | + return nil if options[:datetime_format] || options[:default_if] || options.key?(:default) |
| 65 | + return association_value(field, ref) if options[:association] |
| 66 | + return nil unless field.extractor.instance_of?(AutoExtractor) |
| 67 | + |
| 68 | + read(field, ref) |
| 69 | + end |
| 70 | + |
| 71 | + # Same as AssociationExtractor#extract + the associated Blueprint's #hashify, for associations with a static |
| 72 | + # blueprint and no :options. nil stays nil, because association_default is unset (see Rendering#compiled_view). |
| 73 | + def association_value(field, ref) |
| 74 | + extractor = field.extractor |
| 75 | + blueprint = field.options[:blueprint] |
| 76 | + view = field.options[:view] || :default |
| 77 | + return nil unless extractor.instance_of?(AssociationExtractor) && |
| 78 | + extractor.instance_variable_get(:@extractor).instance_of?(AutoExtractor) && |
| 79 | + blueprint.is_a?(Class) && field.options[:options].nil? && blueprint.view?(view) |
| 80 | + |
| 81 | + "((a = #{read(field, ref)}).nil? ? nil : ::Blueprinter::ViewCompiler.render_association(a, " \ |
| 82 | + "#{ref.call(blueprint)}, #{ref.call(view)}, options))" |
| 83 | + end |
| 84 | + |
| 85 | + # Same as AutoExtractor reading a value: BlockExtractor's calling convention, or PublicSendExtractor |
| 86 | + def read(field, ref) |
| 87 | + block = field.options[:block] |
| 88 | + if block |
| 89 | + call_args = block.parameters == [[:req], [:rest]] ? 'object' : 'object, **options' |
| 90 | + "#{ref.call(block)}.call(#{call_args})" |
| 91 | + elsif field.method.to_s.match?(CALLABLE_METHOD) |
| 92 | + "object.#{field.method}" |
| 93 | + else |
| 94 | + "object.public_send(#{ref.call(field.method)})" |
| 95 | + end |
| 96 | + end |
| 97 | + |
| 98 | + # The steps of Rendering#hashify after its view check (done at compile time): extensions, then the same work as |
| 99 | + # prepare_data. The global settings were already checked for this render, so the child's compiled view is used |
| 100 | + # directly; options are only copied when the view differs, since their content would be the same. |
| 101 | + def render_association(value, blueprint, view, options) |
| 102 | + config = Blueprinter.configuration |
| 103 | + value = config.extensions.pre_render(value, blueprint, view, options) unless config.extensions.empty? |
| 104 | + options = options.merge(view:) unless options[:view] == view |
| 105 | + compiled = blueprint.view_collection.compiled(view) |
| 106 | + |
| 107 | + if config.array_like_classes.any? { |klass| value.is_a?(klass) } |
| 108 | + value.map { |item| render_one(item, blueprint, view, options, compiled) } |
| 109 | + else |
| 110 | + render_one(value, blueprint, view, options, compiled) |
| 111 | + end |
| 112 | + end |
| 113 | + |
| 114 | + # Hashes use standard rendering, like in Rendering#prepare_data |
| 115 | + def render_one(object, blueprint, view, options, compiled) |
| 116 | + return compiled.call(object, options) unless object.is_a?(Hash) |
| 117 | + |
| 118 | + blueprint.__send__(:object_to_hash, object, view_name: view, local_options: options) |
| 119 | + end |
| 120 | + |
| 121 | + def statement(field, key, value, ref) |
| 122 | + unless value |
| 123 | + # Standard rendering for this field |
| 124 | + field_ref = ref.call(field) |
| 125 | + value = "#{field_ref}.extract(object, options)" |
| 126 | + condition = "!#{field_ref}.skip?(#{key}, object, options)" |
| 127 | + end |
| 128 | + condition ||= field_conditions(field, key, ref) |
| 129 | + store = field.options[:exclude_if_nil] ? "v = #{value}\nh[#{key}] = v unless v.nil?" : "h[#{key}] = #{value}" |
| 130 | + condition ? "if #{condition}\n#{store}\nend" : store |
| 131 | + end |
| 132 | + |
| 133 | + # Same as Field#skip? for field-level if/unless (global ones are excluded by Rendering#prepare_data) |
| 134 | + def field_conditions(field, key, ref) |
| 135 | + parts = [] |
| 136 | + parts << "#{ref.call(field.send(:if_callable))}.call(#{key}, object, options)" if field.options[:if] |
| 137 | + parts << "!#{ref.call(field.send(:unless_callable))}.call(#{key}, object, options)" if field.options[:unless] |
| 138 | + parts.empty? ? nil : parts.join(' && ') |
| 139 | + end |
| 140 | + |
| 141 | + # Unconditional fields that are always stored and whose name is not repeated can go in the Hash literal |
| 142 | + def literal_field?(field, keys) |
| 143 | + !field.options[:if] && !field.options[:unless] && !field.options[:exclude_if_nil] && !keys.key?(field.name) |
| 144 | + end |
| 145 | + |
| 146 | + def key_for(name, ref) |
| 147 | + name.is_a?(Symbol) && name.to_s.match?(LITERAL_SYMBOL) ? ":#{name}" : ref.call(name) |
| 148 | + end |
| 149 | + end |
| 150 | +end |
0 commit comments