Module: T::Props::Serializable::DecoratorMethods

Includes:
HasLazilySpecializedMethods::DecoratorMethods
Defined in:
lib/types/props/serializable.rb

Overview

NB: This must stay in the same file where T::Props::Serializable is defined due to T::Props::Decorator#apply_plugin; see https://git.corp.stripe.com/stripe-internal/pay-server/blob/fc7f15593b49875f2d0499ffecfd19798bac05b3/chalk/odm/lib/chalk-odm/document_decorator.rb#L716-L717

Instance Method Summary collapse

Methods included from HasLazilySpecializedMethods::DecoratorMethods

#eagerly_define_lazy_methods!, #eagerly_define_lazy_vm_methods!

Methods included from Sig

#sig

Methods included from T::Private::Methods::SingletonMethodHooks

#singleton_method_added

Methods included from T::Private::Methods::MethodHooks

#method_added

Instance Method Details

#add_prop_definition(prop, rules) ⇒ Object



208
209
210
211
212
213
214
215
216
# File 'lib/types/props/serializable.rb', line 208

def add_prop_definition(prop, rules)
  serialized_form = rules.fetch(:name, prop.to_s)
  rules[:serialized_form] = serialized_form
  res = super
  prop_by_serialized_forms[serialized_form] = prop
  enqueue_lazy_method_definition!(:__t_props_generated_serialize) { generate_serialize_source }
  enqueue_lazy_method_definition!(:__t_props_generated_deserialize) { generate_deserialize_source }
  res
end

#extra_props(instance) ⇒ Object



316
317
318
# File 'lib/types/props/serializable.rb', line 316

def extra_props(instance)
  instance.instance_variable_get(:@_extra_props) || EMPTY_EXTRA_PROPS
end

#from_hash(hash, strict = false) ⇒ Object

Raises:

  • (ArgumentError)


191
192
193
194
195
196
197
198
# File 'lib/types/props/serializable.rb', line 191

def from_hash(hash, strict=false)
  raise ArgumentError.new("#{hash.inspect} provided to from_hash") if !(hash && hash.is_a?(Hash))

  i = @class.allocate
  i.deserialize(hash, strict)

  i
end

#get_id(instance) ⇒ Object



304
305
306
307
308
309
310
311
# File 'lib/types/props/serializable.rb', line 304

def get_id(instance)
  prop = prop_by_serialized_forms['_id']
  if prop
    get(instance, prop)
  else
    nil
  end
end

#message_with_generated_source_context(error, generated_method, generate_source_method) ⇒ Object



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/types/props/serializable.rb', line 229

def message_with_generated_source_context(error, generated_method, generate_source_method)
  generated_method = generated_method.to_s
  if error.backtrace_locations
    line_loc = error.backtrace_locations.find { |l| l.base_label == generated_method }
    return unless line_loc

    line_num = line_loc.lineno
  else
    label = if RUBY_VERSION >= "3.4"
      # in 'ClassName#__t_props_generated_serialize'"
      "##{generated_method}'"
    else
      # in `__t_props_generated_serialize'"
      "in `#{generated_method}'"
    end
    line_label = error.backtrace.find { |l| l.end_with?(label) }
    return unless line_label

    line_num = if line_label.start_with?("(eval)")
      # (eval):13:in ...
      line_label.split(':')[1]&.to_i
    else
      # (eval at /Users/jez/stripe/sorbet/gems/sorbet-runtime/lib/types/props/has_lazily_specialized_methods.rb:65):13:in ...
      line_label.split(':')[2]&.to_i
    end
  end
  return unless line_num

  source_lines = self.send(generate_source_method).split("\n")
  previous_blank = source_lines[0...line_num].rindex(&:empty?) || 0
  next_blank = line_num + (source_lines[line_num..-1]&.find_index(&:empty?) || 0)
  context = "  #{source_lines[(previous_blank + 1)...next_blank].join("\n  ")}"
  "    Error in \#{decorated_class.name}#\#{generated_method}: \#{error.message}\n    at line \#{line_num - previous_blank - 1} in:\n    \#{context}\n  MSG\nend\n"

#pretty_print_extra(instance, pp) ⇒ Object

adds to the default result of T::Props::PrettyPrintable



321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/types/props/serializable.rb', line 321

def pretty_print_extra(instance, pp)
  # This is to maintain backwards compatibility with Stripe's codebase, where only the single line (through `inspect`)
  # version is expected to add anything extra
  return if !pp.is_a?(PP::SingleLine)
  if (extra_props = extra_props(instance)) && !extra_props.empty?
    pp.breakable
    pp.text("@_extra_props=")
    pp.group(1, "<", ">") do
      extra_props.each_with_index do |(prop, value), i|
        pp.breakable unless i.zero?
        pp.text("#{prop}=")
        value.pretty_print(pp)
      end
    end
  end
end

#prop_by_serialized_formsObject



187
188
189
# File 'lib/types/props/serializable.rb', line 187

def prop_by_serialized_forms
  @class.prop_by_serialized_forms
end

#prop_dont_store?(prop) ⇒ Boolean

Returns:



184
185
186
# File 'lib/types/props/serializable.rb', line 184

def prop_dont_store?(prop)
  prop_rules(prop)[:dont_store]
end

#prop_serialized_form(prop) ⇒ Object



200
201
202
# File 'lib/types/props/serializable.rb', line 200

def prop_serialized_form(prop)
  prop_rules(prop)[:serialized_form]
end

#prop_validate_definition!(name, cls, rules, type) ⇒ Object



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/types/props/serializable.rb', line 274

def prop_validate_definition!(name, cls, rules, type)
  result = super

  if (rules_name = rules[:name])
    unless rules_name.is_a?(String)
      raise ArgumentError.new("Invalid name in prop #{@class.name}.#{name}: #{rules_name.inspect}")
    end

    validate_prop_name(rules_name)
  end

  if !rules[:raise_on_nil_write].nil? && rules[:raise_on_nil_write] != true
    raise ArgumentError.new("The value of `raise_on_nil_write` if specified must be `true` (given: #{rules[:raise_on_nil_write]}).")
  end

  if rules[:raise_on_nil_write] && !rules[:_tnilable]
    is_nilclass_parent = type.is_a?(T::Types::Simple) &&
                         (type.raw_type.equal?(Object) || type.raw_type.equal?(BasicObject))
    # Use `instance_of?` because modules can be mixed into NilClass, but classes cannot.
    is_module = type.is_a?(T::Types::Simple) && type.raw_type.instance_of?(Module)
    underspecified_type = type.equal?(T.untyped) || is_nilclass_parent || is_module

    unless underspecified_type
      raise ArgumentError.new("`raise_on_nil_write` requires that the type of `#{name}` be `T.nilable(...)` (given: #{type})")
    end
  end

  result
end

#raise_nil_deserialize_error(hkey) ⇒ Object



268
269
270
271
272
# File 'lib/types/props/serializable.rb', line 268

def raise_nil_deserialize_error(hkey)
  raise "Tried to deserialize a required prop from a nil value. " \
    "You should provide a `default: or factory:` for this prop. " \
    "prop=#{hkey} klass=#{decorated_class.name}"
end

#required_propsObject



180
181
182
# File 'lib/types/props/serializable.rb', line 180

def required_props
  @class.props.select { |_, v| T::Props::Utils.required_prop?(v) }.keys
end

#serialized_form_prop(serialized_form) ⇒ Object



204
205
206
# File 'lib/types/props/serializable.rb', line 204

def serialized_form_prop(serialized_form)
  prop_by_serialized_forms[serialized_form.to_s] || raise("No such serialized form: #{serialized_form.inspect}")
end

#valid_rule_key?(key) ⇒ Boolean

Returns:



176
177
178
# File 'lib/types/props/serializable.rb', line 176

def valid_rule_key?(key)
  super || VALID_RULE_KEYS[key]
end