Sha256: 7cb2524717298eaee667db6c309f75993bfe4bf3280091ccf5e62a286b1963dc

Contents?: true

Size: 721 Bytes

Versions: 2

Compression:

Stored size: 721 Bytes

Contents

require_relative "instance_variables_from/version"

module Kernel
  private

  def instance_variables_from(obj, *whitelist)
    values_to_assign = case obj
    when Binding
      obj.eval('local_variables').map{ |e| [obj.eval("#{e}"), e] }
    when Hash
      obj.map{|k,v| [v,k] }
    when Array
      obj.each.with_index
    else
      raise ArgumentError, "cannot extract instance_variables from #{obj}"
    end

    unless whitelist.empty?
      values_to_assign.select!{ |value, key| whitelist.include? key.to_sym }
    end

    values_to_assign.map{ |value, key|
      key = key.to_s
      ivar_name = :"@#{'_' if key =~ /\A\d/}#{key}"
      instance_variable_set(ivar_name, value)
      ivar_name
    }
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
instance_variables_from-1.0.1 lib/instance_variables_from.rb
instance_variables_from-1.0.0 lib/instance_variables_from.rb