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



211
212
213
214
215
216
217
218
219
# File 'lib/types/props/serializable.rb', line 211

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



307
308
309
# File 'lib/types/props/serializable.rb', line 307

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

#from_hash(hash, strict = false) ⇒ Object

Raises:

  • (ArgumentError)


194
195
196
197
198
199
200
201
# File 'lib/types/props/serializable.rb', line 194

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



295
296
297
298
299
300
301
302
# File 'lib/types/props/serializable.rb', line 295

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



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
267
268
269
# File 'lib/types/props/serializable.rb', line 232

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  ")}"
  <<~MSG
    Error in #{decorated_class.name}##{generated_method}: #{error.message}
    at line #{line_num - previous_blank - 1} in:
    #{context}
  MSG
end

#pretty_print_extra(instance, pp) ⇒ Object

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



312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/types/props/serializable.rb', line 312

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



190
191
192
# File 'lib/types/props/serializable.rb', line 190

def prop_by_serialized_forms
  @class.prop_by_serialized_forms
end

#prop_dont_store?(prop) ⇒ Boolean

Returns:



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

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

#prop_serialized_form(prop) ⇒ Object



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

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

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



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/types/props/serializable.rb', line 277

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

  result
end

#raise_nil_deserialize_error(hkey) ⇒ Object



271
272
273
274
275
# File 'lib/types/props/serializable.rb', line 271

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



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

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

#serialized_form_prop(serialized_form) ⇒ Object



207
208
209
# File 'lib/types/props/serializable.rb', line 207

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:



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

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