Module: SelectiveAttributeProxy

Included in:
Aliyun::OSS::Logging::Status, Aliyun::OSS::OSSObject, Aliyun::OSS::Owner
Defined in:
lib/aliyun/oss/extensions.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



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
# File 'lib/aliyun/oss/extensions.rb', line 265

def self.included(klass)
  klass.extend(ClassMethods)
  klass.class_eval(<<-EVAL, __FILE__, __LINE__)
    cattr_accessor :attribute_proxy
    cattr_accessor :attribute_proxy_options
    
    # Default name for attribute storage
    self.attribute_proxy         = :attributes
    self.attribute_proxy_options = {:exclusively => true}
    
    private
      # By default proxy all attributes
      def proxiable_attribute?(name)
        return true unless self.class.attribute_proxy_options[:exclusively]
        send(self.class.attribute_proxy).has_key?(name)
      end
      
      def method_missing(method, *args, &block)
        # Autovivify attribute storage
        if method == self.class.attribute_proxy
          ivar = "@\#{method}"
          instance_variable_set(ivar, {}) unless instance_variable_get(ivar).is_a?(Hash)
          instance_variable_get(ivar)
        # Delegate to attribute storage
        elsif method.to_s =~ /^(\\w+)(=?)$/ && proxiable_attribute?($1)
          attributes_hash_name = self.class.attribute_proxy
          $2.empty? ? send(attributes_hash_name)[$1] : send(attributes_hash_name)[$1] = args.first
        else
          super
        end
      end
  EVAL
end