Module: NRSER::Props

Defined in:
lib/nrser/props/metadata.rb,
lib/nrser/props/prop.rb,
lib/nrser/props/class_methods.rb,
lib/nrser/props/instance_methods.rb,
lib/nrser/props/immutable/hash_variable.rb,
lib/nrser/props.rb

Overview

Declarations

Defined Under Namespace

Modules: ClassMethods, Immutable, InstanceMethods, Mutable, Storage Classes: Metadata, Prop

Constant Summary collapse

DEFAULT_CLASS_KEY =
'__class__'

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



12
13
14
15
# File 'lib/nrser/props.rb', line 12

def self.included base
  base.include  NRSER::Props::InstanceMethods
  base.extend   NRSER::Props::ClassMethods
end

.UNSAFE_load_instance_from_data(data, class_key: DEFAULT_CLASS_KEY) ⇒ NRSER::Props::Props

Instantiate a class from a data hash. The hash must contain the ‘__class__` key and the target class must be loaded already.

WARNING

I’m sure this is all-sorts of unsafe. Please don’t ever think this is reasonable to use on untrusted data.

Parameters:

Returns:

  • (NRSER::Props::Props)

    Instance of a propertied class.



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/nrser/props.rb', line 33

def self.UNSAFE_load_instance_from_data data, class_key: DEFAULT_CLASS_KEY
  t.hash_.check data
  
  unless data.key?( class_key )
    raise ArgumentError.new binding.erb <<-ERB
      Data is missing <%= class_key %> key - no idea what class to
      instantiate.
      
      Data:
      
          <%= data.pretty_inspect %>
      
    ERB
  end
  
  # Get the class name from the data hash using the key, checking that it's
  # a non-empty string.
  class_name = t.non_empty_str.check! data[class_key]
  
  # Resolve the constant at that name.
  klass = class_name.to_const!
  
  # Make sure it's one of ours
  unless klass.included_modules.include?( NRSER::Props )
    raise ArgumentError.new binding.erb <<-ERB
      Can not load instance from data - bad class name.
      
      Extracted class name
      
          <%= class_name.inspect %>
      
      from class key
      
          <%= class_key.inspect %>
      
      which resolved to constant
      
          <%= klass.inspect %>
      
      but that class does not include the NRSER::Props::Props mixin, which we
      check for to help protect against executing an unrelated `.from_data`
      class method when attempting to load.
      
      Data:
      
          <%= data.pretty_inspect %>
      
    ERB
  end
  
  # Kick off the restore and return the result
  klass.from_data data
  
end