Sha256: 8744e001225b1c28dfa84a1d9f6571b776cee7925c28af12091c9eb08651010d

Contents?: true

Size: 1.52 KB

Versions: 19

Compression:

Stored size: 1.52 KB

Contents

require 'facet/kernel/set_from'

module Kernel

  # Assign via setter methods using a hash (or assoc array).
  #
  #   object.set_with( :a => 1, :b => 2 )
  #   object.set_with( :a, 1, :b, 2 )
  #   object.set_with( [:a, 1], [:b, 2] )
  #   object.set_with( *[[:a, 1], [:b, 2]] )
  #
  # These are all the same as doing:
  #
  #   object.a = 1
  #   object.b = 2
  #
  # The array forms gaurentees order of operation.
  #
  def set_with(*args)
    harg = args.last.is_a?(Hash) ? args.pop : {}

    unless args.empty?
      # if not assoc array, eg. [ [], [], ... ]
      # preserves order of opertation
      unless args[0].is_a?(Array)
        i = 0; a = []
        while i < args.size
          a << [ args[i], args[i+1] ]
          i += 2
        end
        args = a
      end
    end

    args.each do |k,v|
      self.send( "#{k}=", v ) #if respond_to?("#{k}=")
    end

    harg.each do |k,v|
      self.send( "#{k}=", v ) #if respond_to?("#{k}=")
    end

  end

end



#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCKernel < Test::Unit::TestCase

    Customer = Struct.new( "Customer", :name, :address, :zip )

    def test_set_with
      bob = Customer.new()
      sethash = { :name => "Bob Sawyer", :address => "123 Maple, Anytown NC", :zip => 12345 }
      bob.set_with(sethash)
      assert_equal("Bob Sawyer", bob.name)
      assert_equal("123 Maple, Anytown NC", bob.address)
      assert_equal(12345, bob.zip)
    end

  end

=end

Version data entries

19 entries across 19 versions & 1 rubygems

Version Path
facets-1.0.0 lib/facet/kernel/set_with.rb
facets-1.0.3 packages/core/lib/facet/kernel/set_with.rb
facets-1.3.0 lib/facets/core/kernel/set_with.rb
facets-1.1.0 lib/facet/kernel/set_with.rb
facets-1.2.0 lib/facets/core/kernel/set_with.rb
facets-1.2.1 lib/facets/core/kernel/set_with.rb
facets-1.3.2 lib/facets/core/kernel/set_with.rb
facets-1.3.1 lib/facets/core/kernel/set_with.rb
facets-1.3.3 lib/facets/core/kernel/set_with.rb
facets-1.4.2 lib/facets/core/kernel/set_with.rb
facets-1.4.0 lib/facets/core/kernel/set_with.rb
facets-1.4.1 lib/facets/core/kernel/set_with.rb
facets-1.4.3 lib/facets/core/kernel/set_with.rb
facets-1.4.5 lib/facets/core/kernel/set_with.rb
facets-1.4.4 lib/facets/core/kernel/set_with.rb
facets-1.7.0 lib/facets/core/kernel/set_with.rb
facets-1.7.30 lib/facets/core/kernel/set_with.rb
facets-1.7.38 lib/facets/core/kernel/set_with.rb
facets-1.7.46 lib/facets/core/kernel/set_with.rb