File: resource.rb

package info (click to toggle)
ruby-aws-sdk 1.67.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,840 kB
  • sloc: ruby: 28,436; makefile: 7
file content (413 lines) | stat: -rw-r--r-- 11,544 bytes parent folder | download | duplicates (4)
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413

# Copyright 2011-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
#     http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.

module AWS
  module Core

    # @api private
    class Resource

      include Model
      include Cacheable

      # @api private
      class NotFound < StandardError; end

      # @api private
      def initialize *args

        super

        # cache static attributes passed into options

        options = args.last.is_a?(Hash) ? args.last : {}
        options.each_pair do |opt_name,opt_value|
          if
            self.class.attributes.has_key?(opt_name) and
            self.class.attributes[opt_name].static?
          then
            static_attributes[opt_name] = opt_value
          end
        end

      end

      # @return [String] Returns a simple string representation of this resource.
      def inspect

        identifiers = []
        resource_identifiers.each do |key, value|
          if attr = self.class.attributes.values.find{|a| a.from == key }
            identifiers << "#{attr.name}:#{value}"
          else
            identifiers << "#{key}:#{value}"
          end
        end

        "<#{self::class} #{identifiers.join(' ')}>"

      end

      # @return [Boolean] Returns true if the objects references the same
      #   AWS resource.
      def eql? other
        other.kind_of?(self.class) and
        other.resource_identifiers == resource_identifiers
      end
      alias_method :==, :eql?

      # @api private
      protected
      def get_resource attr_name
        raise NotImplementedError
      end

      # @api private
      protected
      def update_resource attr, value
        raise NotImplementedError
      end

      # Overide this method is subclasses of Resource.  This method should
      # return an array of identifying key/value pairs.
      #
      #     # @api private
      #     protected
      #     def resource_identifiers
      #       [[:user_name, name]]
      #     end
      #
      # @api private
      protected
      def resource_identifiers
        raise NotImplementedError
      end

      # @protected
      protected
      def resource_options(additional = {})
        Hash[resource_identifiers].merge(additional)
      end

      # @api private
      protected
      def local_cache_key
        resource_identifiers.collect{|name,value| value.to_s }.join(":")
      end

      # @api private
      protected
      def static_attributes
        @static_attributes ||= {}
      end

      # @api private
      protected
      def ruby_name
        @ruby_name ||= Inflection.ruby_name(self.class.name)
      end

      # @api private
      public
      def attributes_from_response resp

        # check each provider for this request type to see if it
        # can find the resource and some of its attributes
        attributes = []
        self.class.attribute_providers_for(resp.request_type).each do |provider|
          attributes << provider.attributes_from_response(self, resp)
        end

        # drop out those that returned no attributesj
        attributes.compact!

        # stop here if nothing was found for this resource
        return nil if attributes.empty?

        # merge the attributes together into a single hash
        attributes = attributes.inject({}) {|hash,attribs| hash.merge(attribs) }

        # cache static attributes
        attributes.each_pair do |attr_name,value|
          if self.class.attributes[attr_name].static?
            static_attributes[attr_name] = value
          end
        end

        attributes

      end

      # @api private
      protected
      def cache_static_attributes request_type, resp_obj
        self.class.attribute_providers_for(request_type).each do |provider|
          attributes = provider.attributes_from_response_object(resp_obj)
          attributes.each_pair do |attr_name,value|
            if self.class.attributes[attr_name].static?
              static_attributes[attr_name] = value
            end
          end
        end
      end

      class << self

        # @api private
        def define_attribute_type type_name
          class_eval <<-METHODS

            def self.#{type_name}_attributes
              @#{type_name}_attributes ||= {}
            end

            def self.#{type_name}_attribute name, options = {}, &block
              attr = attribute(name, options, &block)
              #{type_name}_attributes[attr.name] = attr
            end

          METHODS
        end

        # @api private
        def new_from request_type, resp_obj, *args
          resource = new(*args)
          resource.send(:cache_static_attributes, request_type, resp_obj)
          resource
        end

        # @api private
        def attributes
          @attributes ||= Hash.new do |hash,attr_name|
            raise "uknown attribute #{attr_name}"
          end
        end

        # @api private
        def attribute_providers
          @attribute_providers ||= []
        end

        # @api private
        def attribute_providers_for request_type
          attribute_providers.select do |provider|
            provider.request_types.include?(request_type)
          end
        end

        # @api private
        protected
        def attribute name, options = {}, &block
          attr = Attribute.new(name, options)
          attr.instance_eval(&block) if block_given?
          define_attribute_getter(attr)
          define_attribute_setter(attr) if attr.mutable?
          alias_method(options[:alias], name) if options[:alias]
          attributes[attr.name] = attr
        end

        # @api private
        protected
        def mutable_attribute name, options = {}, &block
          attribute(name, options.merge(:mutable => true), &block)
        end

        # @api private
        protected
        def define_attribute_getter attribute
          define_method(attribute.name) do

            return static_attributes[attribute.name] if
              static_attributes.has_key?(attribute.name)

            begin
              retrieve_attribute(attribute) { get_resource(attribute) }
            rescue Cacheable::NoData => e
              name = ruby_name.tr("_", " ")
              raise NotFound, "unable to find the #{name}"
            end

          end
        end

        # @api private
        protected
        def define_attribute_setter attribute
          setter = attribute.name.to_s.sub(/\?/, '') + '='
          define_method(setter) do |value|
            translated_value = attribute.translate_input_value(value)
            update_resource(attribute, translated_value)
            if attribute.static?
              static_attributes[attribute.name] = translated_value
            end
            value
          end
        end

        # @api private
        protected
        def populates_from *request_types, &block
          provider = provider(*request_types)
          provider.find(&block)
          provider.provides(*attributes.keys)
          provider
        end

        # @api private
        protected
        def provider *request_types, &block
          provider = AttributeProvider.new(self, request_types)
          if block_given?
            yield(provider)
          end
          attribute_providers << provider
          provider
        end

      end

      # @api private
      class Attribute

        def initialize name, options = {}
          @name = name
          @options = options
          @request_types = []
        end

        attr_reader :name

        attr_reader :request_types

        def from
          @from ||= (@options[:from] || name)
        end

        def set_as
          @set_as ||= (@options[:set_as] || @options[:from] || name)
        end

        def mutable?
          @options[:mutable] == true
        end

        def static?
          @options[:static] == true
        end

        def translates_input &block
          @input_translator = block
        end

        def translates_output options = {}, &block
          @translates_nil = options[:nil]
          @output_translator = block
        end

        def translate_input_value value
          @input_translator ? @input_translator.call(value) : value
        end

        def translate_output_value value

          # by default nil values are not translated
          return nil if value.nil? and @translates_nil != true

          case
          when @options[:to_sym]    then value.tr('-','_').downcase.to_sym
          when @options[:timestamp] then Time.at(value.to_i)
          when @output_translator   then @output_translator.call(value)
          else value
          end

        end

      end

      # @api private
      class AttributeProvider

        def initialize klass, request_types
          @klass = klass
          @id = klass.attribute_providers.length
          @request_types = request_types
          @provides = {}
        end

        attr_reader :request_types

        def find &block
          @klass.send(:define_method, finder_method, &block)
        end

        def finder_method
          "_find_in_#{request_types.join('_or_')}_response_#{@id}"
        end

        # Indicates that all of the the named attributes can be retrieved
        # from an appropriate response object.
        #
        # @overload provides(*attr_names, options = {})
        #   @param [Symbol] attr_names A list of attributes provided
        #   @param [Hash] options
        #   @option options [Boolean] :value_wrapped (false) If true, then
        #     the value returned by the response object will also receive
        #     the message :value before it is translated and returned.
        #   @option options [Symbol] :from Defaults to the method named
        #     by the attribute.  This is useful when you have two providers
        #     for the same attribute but their response object name
        #     them differently.
        def provides *attr_names
          options = attr_names.last.is_a?(Hash) ? attr_names.pop : {}
          attr_names.each do |attr_name|
            attr = @klass.attributes[attr_name]
            attr.request_types.push(*request_types)
            @provides[attr_name] = options
          end
        end

        def attributes_from_response resource, response
          if response_object = resource.send(finder_method, response)
            attributes_from_response_object(response_object)
          else
            nil
          end
        end

        def attributes_from_response_object resp_obj

          @provides.inject({}) do |attributes,(attr_name,options)|

            attr = @klass.attributes[attr_name]

            methods = [options[:from] || attr.from].flatten

            v = resp_obj
            methods.each do |method|
              v = v.key?(method) ? v[method] : v[method.to_s]
              break if v.nil?
            end
            v = v[:value] if v and options[:value_wrapped]
            v = attr.translate_output_value(v)

            attributes.merge(attr_name => v)

          end

        end

      end
    end
  end
end