File: data.rb

package info (click to toggle)
ruby-vagrant-cloud 3.0.5-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 408 kB
  • sloc: ruby: 4,343; makefile: 7
file content (293 lines) | stat: -rw-r--r-- 8,126 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
module VagrantCloud
  # Generic data class which provides simple attribute
  # data storage using a Hash like interface
  class Data
    # Custom nil class which is used for signifying
    # a nil value that was not set by the user. This
    # makes it easy to filter out values which are
    # unset vs. those that are set to nil.
    class NilClass < BasicObject
      include ::Singleton
      def nil?; true; end
      def ==(v); v.nil? || super(v); end
      def ===(v); equal?(v); end
      def equal?(v); v.nil? || super(v); end
      def to_i; 0; end
      def to_f; 0.0; end
      def to_a; []; end
      def to_h; {}; end
      def to_s; ""; end
      def &(_); false; end
      def |(_); false; end
      def ^(_); false; end
      def !; true; end
      def inspect; 'nil'; end
    end

    # Easy to use constant to access general
    # use instance of our custom nil class
    Nil = NilClass.instance

    # Create a new instance
    #
    # @return [Data]
    def initialize(**opts)
      @data = opts
    end

    # Fetch value from data
    #
    # @param [String, Symbol] k Name of value
    # @return [Object]
    def [](k)
      @data.key?(k.to_sym) ? @data[k.to_sym] : Nil
    end

    # @return [String]
    def inspect
      "<#{self.class.name}:#{sprintf("%#x", object_id)}>"
    end

    protected def data; @data; end

    # Immutable data class. This class adds extra functionality to the Data
    # class like providing attribute methods which can be defined using the
    # `attr_required` and `attr_optional` methods. Once an instance is created
    # the data is immutable. For example:
    #
    # class MyData < Immutable
    #   attr_required :name
    #   attr_optional :version
    # end
    #
    # When creating a new instance, a name parameter _must_ be provided,
    # but a version parameter is optional, so both are valid:
    #
    # instance = MyData.new(name: "testing", version: "new-version")
    #
    # and
    #
    # instance = MyData.new(name: "testing")
    #
    # but only providing the version is invalid:
    #
    # instance = MyData.new(version: "new-version") # -> Exception
    class Immutable < Data
      @@lock = Mutex.new

      # Define attributes which are required
      def self.attr_required(*args)
        return @required || [] if args.empty?
        sync do
          @required ||= []
          if !args.empty?
            # Create any accessor methods which do not yet exist
            args = args.map(&:to_sym) - @required
            args.each do |argument_name|
              if !method_defined?(argument_name)
                define_method(argument_name) {
                  send(:[], argument_name.to_sym)
                }
              end
            end
            @required += args
          end
          @required
        end
      end

      # Define attributes which are optional
      def self.attr_optional(*args)
        return @optional || [] if args.empty?
        sync do
          @optional ||= []
          if !args.empty?
            # Create any accessor method which do not yet exist
            args = args.map(&:to_sym) - @optional
            args.each do |argument_name|
              if !method_defined?(argument_name)
                define_method(argument_name) {
                  send(:[], argument_name.to_sym)
                }
              end
            end
            @optional += args
          end
          @optional
        end
      end

      # If inherited, set attribute information
      def self.inherited(klass)
        klass.attr_required(*attr_required)
        klass.attr_optional(*attr_optional)
        klass.class_variable_set(:@@lock, Mutex.new)
      end

      # Synchronize action
      def self.sync
        @@lock.synchronize do
          yield
        end
      end

      # Create a new instance
      #
      # @return [Immutable]
      def initialize(**opts)
        super()
        self.class.attr_required.each do |attr|
          if !opts.key?(attr)
            raise ArgumentError, "Missing required parameter `#{attr}`"
          end
          data[attr.to_sym] = opts[attr].dup
        end
        self.class.attr_optional.each do |attr|
          if opts.key?(attr)
            data[attr.to_sym] = opts[attr].dup
          end
        end
        extras = opts.keys - (self.class.attr_required + self.class.attr_optional)
        if !extras.empty?
          raise ArgumentError, "Unknown parameters provided: #{extras.join(",")}"
        end
        freezer(@data)
      end

      # @return [String]
      def inspect
        vars = (self.class.attr_required + self.class.attr_optional).map do |k|
          val = self.send(:[], k)
          next if val.nil? || val.to_s.empty?
          "#{k}=#{val.inspect}"
        end.compact.join(", ")
        "<#{self.class.name}:#{sprintf("%#x", object_id)} #{vars}>"
      end

      protected

      # Freeze the given object and all nested
      # objects that can be found
      #
      # @return [Object]
      def freezer(obj)
        if obj.is_a?(Enumerable)
          obj.each do |item|
            freezer(item)
            item.freeze
          end
        end
        obj.freeze
      end
    end

    # Mutable data class
    class Mutable < Immutable
      # Define attributes which are mutable
      def self.attr_mutable(*args)
        sync do
          args.each do |attr|
            if !attr_required.include?(attr.to_sym) && !attr_optional.include?(attr.to_sym)
              raise ArgumentError, "Unknown attribute name provided `#{attr}`"
            end
            define_method("#{attr}=") { |v| dirty[attr.to_sym] = v }
          end
        end
      end

      # Load data and create a new instance
      #
      # @param [Hash] options Value to initialize instance
      # @return [Mutable]
      def self.load(options={})
        opts = {}.tap do |o|
          (attr_required + attr_optional +
            self.instance_method(:initialize).parameters.find_all { |i|
            i.first == :key || i.first == :keyreq
          }.map(&:last)).each do |k|
            o[k.to_sym] = options[k.to_sym]
          end
        end
        self.new(**opts)
      end

      # Create a new instance
      #
      # @return [Mutable]
      def initialize(**opts)
        super
        @dirty = {}
      end

      # Fetch value from data
      #
      # @param [String, Symbol] k Name of value
      # @return [Object]
      def [](k)
        if dirty?(k)
          @dirty[k.to_sym]
        else
          super
        end
      end

      # Check if instance is dirty or specific
      # attribute if key is provided
      #
      # @param [Symbol] key Key to check
      # @return [Boolean] instance is dirty
      def dirty?(key=nil, **opts)
        if key.nil?
          !@dirty.empty?
        else
          @dirty.key?(key.to_sym)
        end
      end

      # Load given data and ignore any fields
      # that are provided. Flush dirty state.
      #
      # @param [Hash] data Attribute data to load
      # @param [Array<Symbol>] ignores Fields to skip
      # @param [Array<Symbol>] only Fields to update
      # @return [self]
      def clean(data:, ignores: [], only: [])
        raise TypeError, "Expected type `Hash` but received `#{data.inspect}`" if
          !data.is_a?(Hash)
        new_data = @data.dup
        ignores = Array(ignores).map(&:to_sym)
        only = Array(only).map(&:to_sym)
        data.each do |k, v|
          k = k.to_sym
          next if ignores.include?(k)
          next if !only.empty? && !only.include?(k)
          if self.respond_to?(k)
            new_data[k] = v
            @dirty.delete(k)
          end
        end
        @data = freezer(new_data)
        self
      end

      # Merge values from dirty cache into data
      #
      # @return [self]
      def clean!
        @data = freezer(@data.merge(@dirty))
        @dirty.clear
        self
      end

      # @return [self] disable freezing
      def freeze
        self
      end

      # @return [Hash] updated attributes
      protected def dirty; @dirty; end
    end
  end

  Nil = Data::Nil
end