title: Merging two ruby objects
body: <p>Question: Is there a concise way in Ruby (and/or Rails) to merge two objects together? </p>
  
  <p>Specifically, I'm trying to figure out something akin to jQuery's <code>$.extend()</code> method, whereas the first object you pass in will have its properties overridden by the second object.</p>
  
  <p>I'm working with a tableless model in Rails 3.2+. When a form submission occurs, the parameters from the submission are used to dynamically populate a User object. That user object is persisted between page requests using Ruby's PStore class, marshalling objects to flat files which can be easily retrieved in the future.</p>
  
  <p>Relevant code:</p>
  
  <pre><code>module Itc
    class User
      include ActiveModel::Validations
      include ActiveModel::Conversion
      include ActionView::Helpers
      extend ActiveModel::Naming
  
      def set_properties( properties = {} )
        properties.each { |k, v|
          class_eval("attr_reader :#{k.to_sym}")
          self.instance_variable_set("@#{k}", v)
        } unless properties.nil?
      end
    end
  end
  </code></pre>
  
  <p>Creation of a user object occurs like this:</p>
  
  <pre><code>user = Itc.User.new( params[:user] )
  user.save()
  </code></pre>
  
  <p>The <code>save()</code> method above is not ActiveRecord's save method, but a method I wrote to do persistence via PStore.</p>
  
  <p>If I have a user object loaded, and I have a form submission, I'd like to do something like this:</p>
  
  <pre><code>merged = existingUserObject.merge(User.new(params[:user])
  </code></pre>
  
  <p>and have the outcome of <code>merged</code> be a user object, with only properties that were changed in the form submission be updated.</p>
  
  <p>If anyone has any ideas about a better way to do this in general, I'm all ears.</p>