Module: NRSER::Props

Defined in:
lib/nrser/props.rb,
lib/nrser/props/prop.rb,
lib/nrser/props/metadata.rb,
lib/nrser/props/class_methods.rb,
lib/nrser/props/instance_methods.rb,
lib/nrser/props/immutable/hash_variable.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



36
37
38
39
# File 'lib/nrser/props.rb', line 36

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:

  • data (Hash<String, Object>)

    Data hash to load from.

  • class_key (String) (defaults to: DEFAULT_CLASS_KEY)

    The key name to look for the class name in.

Returns:

  • (NRSER::Props::Props)

    Instance of a propertied class.



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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/nrser/props.rb', line 58

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