Sha256: d2b9d1d4ef80bbf5bf6b700c019509c263b7e570e3dba2e09d5329d7df350544

Contents?: true

Size: 1.36 KB

Versions: 22

Compression:

Stored size: 1.36 KB

Contents

require 'facet/kernel/set_with'

module Kernel

  # Set setter methods using a another object.
  #
  #   class X
  #     attr_accessor :a, :b
  #     def initialize( a, b )
  #        @a,@b = a,b
  #     end
  #   end
  #
  #   obj1 = X.new( 1, 2 )
  #   obj2 = X.new
  #
  #   obj2.set_from(obj1)
  #
  #   obj2.a  #=> 1
  #   obj2.b  #=> 2
  #
  def set_from(obj, *fields)
    unless fields.empty?
      fields.each do |k|
        send( "#{k}=", obj.send("#{k}") )  #if self.respond_to?("#{k}=") && obj.respond_to?("#{k}")
      end
    else
      setters = methods.collect { |m| m =~ /=$/ }
      setters.each do |setter|
        getter = setter.chomp('=')
        if obj.respond_to?(getter)
          send( setter, obj.send(getter) )
          fields < getter
        end
      end
    end
    fields
  end

end



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

  require 'test/unit'

  class TCKernel < Test::Unit::TestCase

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

    def test_set_from
      bob = Customer.new("Bob Sawyer", "123 Maple, Anytown NC", 12345)
      joe = Customer.new("Joe Pitare")
      joe.set_from(bob, :address, :zip)
      assert_equal("Joe Pitare", joe.name)
      assert_equal("123 Maple, Anytown NC", joe.address)
      assert_equal(12345, joe.zip)  
    end

  end

=end

Version data entries

22 entries across 22 versions & 1 rubygems

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