File: active_support/core_ext/object/instance_variables.rb

Code

Code

   1  class Object
   2    # Available in 1.8.6 and later.
   3    unless respond_to?(:instance_variable_defined?)
   4      def instance_variable_defined?(variable)
   5        instance_variables.include?(variable.to_s)
   6      end
   7    end
   8 
   9    # Returns a hash that maps instance variable names without "@" to their
  10    # corresponding values. Keys are strings both in Ruby 1.8 and 1.9.
  11    #
  12    #   class C
  13    #     def initialize(x, y)
  14    #       @x, @y = x, y
  15    #     end
  16    #   end
  17    #   
  18    #   C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
  19    def instance_values #:nodoc:
  20      instance_variables.inject({}) do |values, name|
  21        values[name.to_s[1..-1]] = instance_variable_get(name)
  22        values
  23      end
  24    end
  25 
  26    # Returns an array of instance variable names including "@". They are strings
  27    # both in Ruby 1.8 and 1.9.
  28    #
  29    #   class C
  30    #     def initialize(x, y)
  31    #       @x, @y = x, y
  32    #     end
  33    #   end
  34    #   
  35    #   C.new(0, 1).instance_variable_names # => ["@y", "@x"]
  36    if RUBY_VERSION >= '1.9'
  37      def instance_variable_names
  38        instance_variables.map { |var| var.to_s }
  39      end
  40    else
  41      alias_method :instance_variable_names, :instance_variables
  42    end
  43 
  44    # Copies the instance variables of +object+ into +self+.
  45    #
  46    # Instance variable names in the +exclude+ array are ignored. If +object+
  47    # responds to <tt>protected_instance_variables</tt> the ones returned are
  48    # also ignored. For example, Rails controllers implement that method.
  49    #
  50    # In both cases strings and symbols are understood, and they have to include
  51    # the at sign.
  52    #
  53    #   class C
  54    #     def initialize(x, y, z)
  55    #       @x, @y, @z = x, y, z
  56    #     end
  57    #   
  58    #     def protected_instance_variables
  59    #       %w(@z)
  60    #     end
  61    #   end
  62    #   
  63    #   a = C.new(0, 1, 2)
  64    #   b = C.new(3, 4, 5)
  65    #   
  66    #   a.copy_instance_variables_from(b, [:@y])
  67    #   # a is now: @x = 3, @y = 1, @z = 2
  68    def copy_instance_variables_from(object, exclude = []) #:nodoc:
  69      exclude += object.protected_instance_variables if object.respond_to? :protected_instance_variables
  70 
  71      vars = object.instance_variables.map(&:to_s) - exclude.map(&:to_s)
  72      vars.each { |name| instance_variable_set(name, object.instance_variable_get(name)) }
  73    end
  74  end