<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Sdrangne</id>
	<title>Expertiza_Wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Sdrangne"/>
	<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Special:Contributions/Sdrangne"/>
	<updated>2026-08-12T00:37:14Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.41.0</generator>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=90019</id>
		<title>CSC/ECE 517 Fall 2014/oss E1458 sst</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=90019"/>
		<updated>2014-10-27T22:39:01Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: /* Moved methods from Response Controller to appropriate models */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''E1458: Expertiza - Refactoring ResponseController'''&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Expertiza==&lt;br /&gt;
[http://wikis.lib.ncsu.edu/index.php/Expertiza Expertiza] is a peer review based course management system. It supports project submission,team creation, and review of the submitted material  including URLs and wiki pages. Students can manage teammates and can conduct reviews on other's topics and projects.&lt;br /&gt;
Expertiza is an open source project based on Ruby on Rails.&lt;br /&gt;
&lt;br /&gt;
== Background==&lt;br /&gt;
As a part of the OSS project 1 we were expected to refactor the Response Controller of Expertiza. Response Controller is responsible for managing the review versions, finding the latest responses and fetching the review scores. This wiki provides a detailed walk through of our contributions to the  Expertiza project with a focus on refactoring.&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
&lt;br /&gt;
The response controller allows the user to create and edit responses to questionnaires such as performing a review, rating a teammate or giving feedback to a reviewer.&lt;br /&gt;
Our project requirement was to perform the following changes :&lt;br /&gt;
* Perform authorization properly.&lt;br /&gt;
* Remove the duplicated methods.&lt;br /&gt;
* Reduce the complexity of the rereview method.&lt;br /&gt;
* Move the functionality incorporated in the controller, to the model, as it is the model's responsibility to implement this functionality.&lt;br /&gt;
&lt;br /&gt;
==Refactoring carried out==&lt;br /&gt;
&lt;br /&gt;
The following changes have been made in the project, as described in the requirements document.&lt;br /&gt;
&lt;br /&gt;
===Perform Authorization correctly===&lt;br /&gt;
&lt;br /&gt;
* Authorization to perform actions was done incorrectly via the redirect_when_disallowed method. It is supposed to be done through the action_allowed? method at the beginning of the class definition. Different authorizations are required for different operations.&lt;br /&gt;
* For example, someone should be allowed to view a response if they wrote the response, or they are the person or on the team whose work the response is applied to, or if they are an instructor or Teaching Assistant for the class.  The person who wrote a response should be allowed to edit it, but not the person/team who was being reviewed, nor the instructor and neither the Teaching Assistant for the class.&lt;br /&gt;
* Earlier, the authorization was handled by denying incorrect access using the redirect_when_disallowed method, which was a more error-prone way of controlling access.  This method has now been removed, and now the class has an action_allowed? method which does the authorization check and allows the user to perform the action only if he/she has the correct permissions.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
'''redirect_when_disallowed''' Method was used for authorization purposes.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def redirect_when_disallowed(response)&lt;br /&gt;
    # For author feedback, participants need to be able to read feedback submitted by other teammates.&lt;br /&gt;
    # If response is anything but author feedback, only the person who wrote feedback should be able to see it.&lt;br /&gt;
    if response.map.read_attribute(:type) == 'FeedbackResponseMap' &amp;amp;&amp;amp; response.map.assignment.team_assignment?&lt;br /&gt;
      team = response.map.reviewer.team&lt;br /&gt;
      unless team.has_user session[:user]&lt;br /&gt;
        redirect_to '/denied?reason=You are not on the team that wrote this feedback'&lt;br /&gt;
      else&lt;br /&gt;
        return false&lt;br /&gt;
      end&lt;br /&gt;
      response.map.read_attribute(:type)&lt;br /&gt;
    end&lt;br /&gt;
    !current_user_id?(response.map.reviewer.user_id)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
We replaced the '''redirect_when_disallowed''' Method by '''action_allowed?''' Method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def action_allowed?&lt;br /&gt;
    case params[:action]&lt;br /&gt;
      when 'view', 'edit', 'delete', 'rereview', 'update'&lt;br /&gt;
        if response.map.read_attribute(:type) == 'FeedbackResponseMap'&lt;br /&gt;
          team = response.map.reviewer.team&lt;br /&gt;
          if team.has_user session[:user]&lt;br /&gt;
           flag= true&lt;br /&gt;
          else&lt;br /&gt;
            flag=false&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flag=true&lt;br /&gt;
    end&lt;br /&gt;
    return flag&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Removal of redundant methods===&lt;br /&gt;
&lt;br /&gt;
* There were two copies of the '''edit, new_feedback and view methods'''.  The second being the newer one, and, according to the rules for method definition, is the one that is currently in use because the latest version overrides the previous versions. We refactored the code by removing the redundant methods for edit, new_feedback and view.&lt;br /&gt;
&lt;br /&gt;
Edit method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def edit&lt;br /&gt;
    @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
    @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
    @return = params[:return]&lt;br /&gt;
    @response = Response.find(params[:id])&lt;br /&gt;
    return if redirect_when_disallowed(@response)&lt;br /&gt;
&lt;br /&gt;
    @map = @response.map&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map_id==@map.map_id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @sorted=@review_scores.sort { |m1, m2| (m1.version_num and m2.version_num) ? m2.version_num &amp;lt;=&amp;gt; m1.version_num : (m1.version_num ? -1 : 1) }&lt;br /&gt;
      @largest_version_num=@sorted[0]&lt;br /&gt;
    end&lt;br /&gt;
    @response = Response.where(map_id: @map.map_id, version_num:  @largest_version_num.version_num).first&lt;br /&gt;
    @modified_object = @response.response_id&lt;br /&gt;
    get_content&lt;br /&gt;
    @review_scores = Array.new&lt;br /&gt;
    @question_type = Array.new&lt;br /&gt;
    @questions.each do |question|&lt;br /&gt;
      @review_scores &amp;lt;&amp;lt; Score.where(response_id: @response.response_id, question_id:  question.id).first&lt;br /&gt;
      @question_type &amp;lt;&amp;lt; QuestionType.find_by_question_id(question.id)&lt;br /&gt;
    end&lt;br /&gt;
    # Check whether this is a custom rubric&lt;br /&gt;
    if @map.questionnaire.section.eql? &amp;quot;Custom&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;custom_update&amp;quot;&lt;br /&gt;
      render :action =&amp;gt; 'custom_response'&lt;br /&gt;
    else&lt;br /&gt;
      # end of special code (except for the end below, to match the if above)&lt;br /&gt;
      #**********************&lt;br /&gt;
      render :action =&amp;gt; 'response'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
New_feedback method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def new_feedback&lt;br /&gt;
    review = Response.find(params[:id])&lt;br /&gt;
    if review&lt;br /&gt;
      reviewer = AssignmentParticipant.where(user_id: session[:user].id, parent_id:  review.map.assignment.id).first&lt;br /&gt;
      map = FeedbackResponseMap.where(reviewed_object_id: review.id, reviewer_id:  reviewer.id).first&lt;br /&gt;
      if map.nil?&lt;br /&gt;
        map = FeedbackResponseMap.create(:reviewed_object_id =&amp;gt; review.id, :reviewer_id =&amp;gt; reviewer.id, :reviewee_id =&amp;gt; review.map.reviewer.id)&lt;br /&gt;
      end&lt;br /&gt;
      redirect_to :action =&amp;gt; 'new', :id =&amp;gt; map.map_id, :return =&amp;gt; &amp;quot;feedback&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      redirect_to :back&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
View method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def view&lt;br /&gt;
    @response = Response.find(params[:id])&lt;br /&gt;
    return if redirect_when_disallowed(@response)&lt;br /&gt;
    @map = @response.map&lt;br /&gt;
    get_content&lt;br /&gt;
    @review_scores = Array.new&lt;br /&gt;
    @question_type = Array.new&lt;br /&gt;
    @questions.each do |question|&lt;br /&gt;
      @review_scores &amp;lt;&amp;lt; Score.where(response_id: @map.response_id, question_id:  question.id).first&lt;br /&gt;
      @question_type &amp;lt;&amp;lt; QuestionType.find_by_question_id(question.id)&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Cleaning up of the rereview moethod===&lt;br /&gt;
* The rereview method was 98 lines long. We refactored the code by turning several parts of it into methods. Now the code is '''81''' lines long.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def rereview&lt;br /&gt;
    @map=ResponseMap.find(params[:id])&lt;br /&gt;
    get_content&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    #get all versions and find the latest version&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map.id==@map.map.id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    latestResponseVersion&lt;br /&gt;
    #sort all the available versions in descending order.&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @sorted=@review_scores.sort { |m1, m2| (m1.version_num and m2.version_num) ? m2.version_num &amp;lt;=&amp;gt; m1.version_num : (m1.version_num ? -1 : 1) }&lt;br /&gt;
      @largest_version_num=@sorted[0]&lt;br /&gt;
      @latest_phase=@largest_version_num.created_at&lt;br /&gt;
      due_dates = DueDate.where([&amp;quot;assignment_id = ?&amp;quot;, @assignment.id])&lt;br /&gt;
      @sorted_deadlines=Array.new&lt;br /&gt;
      @sorted_deadlines=due_dates.sort { |m1, m2| (m1.due_at and m2.due_at) ? m1.due_at &amp;lt;=&amp;gt; m2.due_at : (m1.due_at ? -1 : 1) }&lt;br /&gt;
      current_time=Time.new.getutc&lt;br /&gt;
      #get the highest version numbered review&lt;br /&gt;
      next_due_date=@sorted_deadlines[0]&lt;br /&gt;
      #check in which phase the latest review was done.&lt;br /&gt;
      for deadline_version in @sorted_deadlines&lt;br /&gt;
        if (@largest_version_num.created_at &amp;lt; deadline_version.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
      for deadline_time in @sorted_deadlines&lt;br /&gt;
        if (current_time &amp;lt; deadline_time.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    #check if the latest review is done in the current phase.&lt;br /&gt;
    #if latest review is in current phase then edit the latest one.&lt;br /&gt;
    #else create a new version and update it.&lt;br /&gt;
    # editing the latest review&lt;br /&gt;
    if (deadline_version.due_at== deadline_time.due_at)&lt;br /&gt;
      #send it to edit here&lt;br /&gt;
      @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @response = Response.find_by_map_id_and_version_num(params[:id], @largest_version_num.version_num)&lt;br /&gt;
      return if redirect_when_disallowed(@response)&lt;br /&gt;
      @modified_object = @response.response_id&lt;br /&gt;
      @map = @response.map&lt;br /&gt;
      get_content&lt;br /&gt;
      @review_scores = Array.new&lt;br /&gt;
      @questions.each {&lt;br /&gt;
          |question|&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; Score.find_by_response_id_and_question_id(@response.response_id, question.id)&lt;br /&gt;
      }&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    else&lt;br /&gt;
      #else create a new version and update it.&lt;br /&gt;
      @header = &amp;quot;New&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
      @feedback = params[:feedback]&lt;br /&gt;
      @map = ResponseMap.find(params[:id])&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @modified_object = @map.map_id&lt;br /&gt;
      get_content&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def rereview&lt;br /&gt;
   @map=ResponseMap.find(params[:id])&lt;br /&gt;
    get_content&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    #get all versions and find the latest version&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map.id==@map.map.id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    @review_scores=response.getAllResponseVersions&lt;br /&gt;
    #sort all the available versions in descending order.&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @largest_version_num = Response.get_largest_version_number(@review_scores)&lt;br /&gt;
      @latest_phase=@largest_version_num.created_at&lt;br /&gt;
      due_dates = DueDate.where([&amp;quot;assignment_id = ?&amp;quot;, @assignment.id])&lt;br /&gt;
&lt;br /&gt;
      @sorted_deadlines = DueDate.sort_deadlines(due_dates)&lt;br /&gt;
      current_time=Time.new.getutc&lt;br /&gt;
      #get the highest version numbered review&lt;br /&gt;
      next_due_date=@sorted_deadlines[0]&lt;br /&gt;
      #check in which phase the latest review was done.&lt;br /&gt;
      for deadline_version in @sorted_deadlines&lt;br /&gt;
        if (@largest_version_num.created_at &amp;lt; deadline_version.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
      for deadline_time in @sorted_deadlines&lt;br /&gt;
        if (current_time &amp;lt; deadline_time.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    #check if the latest review is done in the current phase.&lt;br /&gt;
    #if latest review is in current phase then edit the latest one.&lt;br /&gt;
    #else create a new version and update it.&lt;br /&gt;
    # editing the latest review&lt;br /&gt;
    if (deadline_version.due_at== deadline_time.due_at)&lt;br /&gt;
      #send it to edit here&lt;br /&gt;
      @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @response = Response.where(map_id: params[:id], version_num:  @largest_version_num.version_num).first&lt;br /&gt;
      @modified_object = @response.response_id&lt;br /&gt;
      @map = @response.map&lt;br /&gt;
      get_content&lt;br /&gt;
      @review_scores = Array.new&lt;br /&gt;
      @questions.each {&lt;br /&gt;
          |question|&lt;br /&gt;
          @review_scores &amp;lt;&amp;lt; Score.where(response_id: @response.response_id, question_id:  question.id).first&lt;br /&gt;
      }&lt;br /&gt;
      #**********************&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
      # Check whether this is Jace's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (check_user_name_jace? &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;)&lt;br /&gt;
          handle_jace_kludge&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
    else&lt;br /&gt;
      #else create a new version and update it.&lt;br /&gt;
      @header = &amp;quot;New&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
      @feedback = params[:feedback]&lt;br /&gt;
      @map = ResponseMap.find(params[:id])&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @modified_object = @map.map_id&lt;br /&gt;
      get_content&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (check_user_name_jace? &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;)&lt;br /&gt;
        handle_jace_kludge&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Creation of a Kludge===&lt;br /&gt;
&lt;br /&gt;
* The rereview method contained a special code to check whether an assignment is “Jace’s assignment”; this was the first assignment that was ever created with a multipart rubric.  It was hard-coded into the system, rather than working on a rubric that was created in the normal way.  It is impossible to remove this code without breaking that assignment. It is now implemented as a separate method named handle_jace_kludge.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
The following code was present in the rereview method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end     &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
We added two methods named 'handle_jace_kludge' and 'check_user_name_jace?'&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def check_user_name_jace?&lt;br /&gt;
    return @assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def handle_jace_kludge&lt;br /&gt;
    # ** if assignment belongs to Jace handle it depending on the assignment id **&lt;br /&gt;
    if @assignment.id &amp;lt; 469&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      render :action =&amp;gt; 'custom_response'&lt;br /&gt;
    else&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Moved methods from Response Controller to appropriate models===&lt;br /&gt;
&lt;br /&gt;
* Sorting review versions is not a controller responsibility; So we moved it to the '''Response model'''. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def self.get_largest_version_number(review_scores)&lt;br /&gt;
    @sorted=@review_scores.sort { |m1, m2| (m1.version_num and m2.version_num) ? m2.version_num &amp;lt;=&amp;gt; m1.version_num : (m1.version_num ? -1 : 1) }&lt;br /&gt;
    @largest_version_num=@sorted[0]&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Similarly, the logic for determining whether a review is current or not(i.e., the review was done during the current assignment phase) is not a controller's responsibility and thus was moved to the '''Response model'''. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 def self.getAllResponseVersions&lt;br /&gt;
    #get all previous versions of responses for the response map.&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.where(map_id: @map.id)&lt;br /&gt;
&lt;br /&gt;
    @prev.each do |element|&lt;br /&gt;
      @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    return @review_scores&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== External Links ==&lt;br /&gt;
&lt;br /&gt;
:1. [http://wikis.lib.ncsu.edu/index.php/Expertiza Expertiza]&lt;br /&gt;
&lt;br /&gt;
:2. [http://152.46.19.211:3000/ VCL Link]&lt;br /&gt;
&lt;br /&gt;
:3. [https://github.com/sjoshi6/expertiza Git repository]&lt;br /&gt;
&lt;br /&gt;
:4. [https://docs.google.com/a/ncsu.edu/document/d/1Z0xjFZu-Zy-xm73YyUVUgFCtfWgRwhN1rZuThoyF-U0/edit Steps to setup Expertiza]&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=90015</id>
		<title>CSC/ECE 517 Fall 2014/oss E1458 sst</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=90015"/>
		<updated>2014-10-27T22:37:55Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: /* Background */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''E1458: Expertiza - Refactoring ResponseController'''&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Expertiza==&lt;br /&gt;
[http://wikis.lib.ncsu.edu/index.php/Expertiza Expertiza] is a peer review based course management system. It supports project submission,team creation, and review of the submitted material  including URLs and wiki pages. Students can manage teammates and can conduct reviews on other's topics and projects.&lt;br /&gt;
Expertiza is an open source project based on Ruby on Rails.&lt;br /&gt;
&lt;br /&gt;
== Background==&lt;br /&gt;
As a part of the OSS project 1 we were expected to refactor the Response Controller of Expertiza. Response Controller is responsible for managing the review versions, finding the latest responses and fetching the review scores. This wiki provides a detailed walk through of our contributions to the  Expertiza project with a focus on refactoring.&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
&lt;br /&gt;
The response controller allows the user to create and edit responses to questionnaires such as performing a review, rating a teammate or giving feedback to a reviewer.&lt;br /&gt;
Our project requirement was to perform the following changes :&lt;br /&gt;
* Perform authorization properly.&lt;br /&gt;
* Remove the duplicated methods.&lt;br /&gt;
* Reduce the complexity of the rereview method.&lt;br /&gt;
* Move the functionality incorporated in the controller, to the model, as it is the model's responsibility to implement this functionality.&lt;br /&gt;
&lt;br /&gt;
==Refactoring carried out==&lt;br /&gt;
&lt;br /&gt;
The following changes have been made in the project, as described in the requirements document.&lt;br /&gt;
&lt;br /&gt;
===Perform Authorization correctly===&lt;br /&gt;
&lt;br /&gt;
* Authorization to perform actions was done incorrectly via the redirect_when_disallowed method. It is supposed to be done through the action_allowed? method at the beginning of the class definition. Different authorizations are required for different operations.&lt;br /&gt;
* For example, someone should be allowed to view a response if they wrote the response, or they are the person or on the team whose work the response is applied to, or if they are an instructor or Teaching Assistant for the class.  The person who wrote a response should be allowed to edit it, but not the person/team who was being reviewed, nor the instructor and neither the Teaching Assistant for the class.&lt;br /&gt;
* Earlier, the authorization was handled by denying incorrect access using the redirect_when_disallowed method, which was a more error-prone way of controlling access.  This method has now been removed, and now the class has an action_allowed? method which does the authorization check and allows the user to perform the action only if he/she has the correct permissions.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
'''redirect_when_disallowed''' Method was used for authorization purposes.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def redirect_when_disallowed(response)&lt;br /&gt;
    # For author feedback, participants need to be able to read feedback submitted by other teammates.&lt;br /&gt;
    # If response is anything but author feedback, only the person who wrote feedback should be able to see it.&lt;br /&gt;
    if response.map.read_attribute(:type) == 'FeedbackResponseMap' &amp;amp;&amp;amp; response.map.assignment.team_assignment?&lt;br /&gt;
      team = response.map.reviewer.team&lt;br /&gt;
      unless team.has_user session[:user]&lt;br /&gt;
        redirect_to '/denied?reason=You are not on the team that wrote this feedback'&lt;br /&gt;
      else&lt;br /&gt;
        return false&lt;br /&gt;
      end&lt;br /&gt;
      response.map.read_attribute(:type)&lt;br /&gt;
    end&lt;br /&gt;
    !current_user_id?(response.map.reviewer.user_id)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
We replaced the '''redirect_when_disallowed''' Method by '''action_allowed?''' Method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def action_allowed?&lt;br /&gt;
    case params[:action]&lt;br /&gt;
      when 'view', 'edit', 'delete', 'rereview', 'update'&lt;br /&gt;
        if response.map.read_attribute(:type) == 'FeedbackResponseMap'&lt;br /&gt;
          team = response.map.reviewer.team&lt;br /&gt;
          if team.has_user session[:user]&lt;br /&gt;
           flag= true&lt;br /&gt;
          else&lt;br /&gt;
            flag=false&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flag=true&lt;br /&gt;
    end&lt;br /&gt;
    return flag&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Removal of redundant methods===&lt;br /&gt;
&lt;br /&gt;
* There were two copies of the '''edit, new_feedback and view methods'''.  The second being the newer one, and, according to the rules for method definition, is the one that is currently in use because the latest version overrides the previous versions. We refactored the code by removing the redundant methods for edit, new_feedback and view.&lt;br /&gt;
&lt;br /&gt;
Edit method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def edit&lt;br /&gt;
    @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
    @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
    @return = params[:return]&lt;br /&gt;
    @response = Response.find(params[:id])&lt;br /&gt;
    return if redirect_when_disallowed(@response)&lt;br /&gt;
&lt;br /&gt;
    @map = @response.map&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map_id==@map.map_id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @sorted=@review_scores.sort { |m1, m2| (m1.version_num and m2.version_num) ? m2.version_num &amp;lt;=&amp;gt; m1.version_num : (m1.version_num ? -1 : 1) }&lt;br /&gt;
      @largest_version_num=@sorted[0]&lt;br /&gt;
    end&lt;br /&gt;
    @response = Response.where(map_id: @map.map_id, version_num:  @largest_version_num.version_num).first&lt;br /&gt;
    @modified_object = @response.response_id&lt;br /&gt;
    get_content&lt;br /&gt;
    @review_scores = Array.new&lt;br /&gt;
    @question_type = Array.new&lt;br /&gt;
    @questions.each do |question|&lt;br /&gt;
      @review_scores &amp;lt;&amp;lt; Score.where(response_id: @response.response_id, question_id:  question.id).first&lt;br /&gt;
      @question_type &amp;lt;&amp;lt; QuestionType.find_by_question_id(question.id)&lt;br /&gt;
    end&lt;br /&gt;
    # Check whether this is a custom rubric&lt;br /&gt;
    if @map.questionnaire.section.eql? &amp;quot;Custom&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;custom_update&amp;quot;&lt;br /&gt;
      render :action =&amp;gt; 'custom_response'&lt;br /&gt;
    else&lt;br /&gt;
      # end of special code (except for the end below, to match the if above)&lt;br /&gt;
      #**********************&lt;br /&gt;
      render :action =&amp;gt; 'response'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
New_feedback method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def new_feedback&lt;br /&gt;
    review = Response.find(params[:id])&lt;br /&gt;
    if review&lt;br /&gt;
      reviewer = AssignmentParticipant.where(user_id: session[:user].id, parent_id:  review.map.assignment.id).first&lt;br /&gt;
      map = FeedbackResponseMap.where(reviewed_object_id: review.id, reviewer_id:  reviewer.id).first&lt;br /&gt;
      if map.nil?&lt;br /&gt;
        map = FeedbackResponseMap.create(:reviewed_object_id =&amp;gt; review.id, :reviewer_id =&amp;gt; reviewer.id, :reviewee_id =&amp;gt; review.map.reviewer.id)&lt;br /&gt;
      end&lt;br /&gt;
      redirect_to :action =&amp;gt; 'new', :id =&amp;gt; map.map_id, :return =&amp;gt; &amp;quot;feedback&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      redirect_to :back&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
View method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def view&lt;br /&gt;
    @response = Response.find(params[:id])&lt;br /&gt;
    return if redirect_when_disallowed(@response)&lt;br /&gt;
    @map = @response.map&lt;br /&gt;
    get_content&lt;br /&gt;
    @review_scores = Array.new&lt;br /&gt;
    @question_type = Array.new&lt;br /&gt;
    @questions.each do |question|&lt;br /&gt;
      @review_scores &amp;lt;&amp;lt; Score.where(response_id: @map.response_id, question_id:  question.id).first&lt;br /&gt;
      @question_type &amp;lt;&amp;lt; QuestionType.find_by_question_id(question.id)&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Cleaning up of the rereview moethod===&lt;br /&gt;
* The rereview method was 98 lines long. We refactored the code by turning several parts of it into methods. Now the code is '''81''' lines long.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def rereview&lt;br /&gt;
    @map=ResponseMap.find(params[:id])&lt;br /&gt;
    get_content&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    #get all versions and find the latest version&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map.id==@map.map.id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    latestResponseVersion&lt;br /&gt;
    #sort all the available versions in descending order.&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @sorted=@review_scores.sort { |m1, m2| (m1.version_num and m2.version_num) ? m2.version_num &amp;lt;=&amp;gt; m1.version_num : (m1.version_num ? -1 : 1) }&lt;br /&gt;
      @largest_version_num=@sorted[0]&lt;br /&gt;
      @latest_phase=@largest_version_num.created_at&lt;br /&gt;
      due_dates = DueDate.where([&amp;quot;assignment_id = ?&amp;quot;, @assignment.id])&lt;br /&gt;
      @sorted_deadlines=Array.new&lt;br /&gt;
      @sorted_deadlines=due_dates.sort { |m1, m2| (m1.due_at and m2.due_at) ? m1.due_at &amp;lt;=&amp;gt; m2.due_at : (m1.due_at ? -1 : 1) }&lt;br /&gt;
      current_time=Time.new.getutc&lt;br /&gt;
      #get the highest version numbered review&lt;br /&gt;
      next_due_date=@sorted_deadlines[0]&lt;br /&gt;
      #check in which phase the latest review was done.&lt;br /&gt;
      for deadline_version in @sorted_deadlines&lt;br /&gt;
        if (@largest_version_num.created_at &amp;lt; deadline_version.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
      for deadline_time in @sorted_deadlines&lt;br /&gt;
        if (current_time &amp;lt; deadline_time.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    #check if the latest review is done in the current phase.&lt;br /&gt;
    #if latest review is in current phase then edit the latest one.&lt;br /&gt;
    #else create a new version and update it.&lt;br /&gt;
    # editing the latest review&lt;br /&gt;
    if (deadline_version.due_at== deadline_time.due_at)&lt;br /&gt;
      #send it to edit here&lt;br /&gt;
      @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @response = Response.find_by_map_id_and_version_num(params[:id], @largest_version_num.version_num)&lt;br /&gt;
      return if redirect_when_disallowed(@response)&lt;br /&gt;
      @modified_object = @response.response_id&lt;br /&gt;
      @map = @response.map&lt;br /&gt;
      get_content&lt;br /&gt;
      @review_scores = Array.new&lt;br /&gt;
      @questions.each {&lt;br /&gt;
          |question|&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; Score.find_by_response_id_and_question_id(@response.response_id, question.id)&lt;br /&gt;
      }&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    else&lt;br /&gt;
      #else create a new version and update it.&lt;br /&gt;
      @header = &amp;quot;New&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
      @feedback = params[:feedback]&lt;br /&gt;
      @map = ResponseMap.find(params[:id])&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @modified_object = @map.map_id&lt;br /&gt;
      get_content&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def rereview&lt;br /&gt;
   @map=ResponseMap.find(params[:id])&lt;br /&gt;
    get_content&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    #get all versions and find the latest version&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map.id==@map.map.id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    @review_scores=response.getAllResponseVersions&lt;br /&gt;
    #sort all the available versions in descending order.&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @largest_version_num = Response.get_largest_version_number(@review_scores)&lt;br /&gt;
      @latest_phase=@largest_version_num.created_at&lt;br /&gt;
      due_dates = DueDate.where([&amp;quot;assignment_id = ?&amp;quot;, @assignment.id])&lt;br /&gt;
&lt;br /&gt;
      @sorted_deadlines = DueDate.sort_deadlines(due_dates)&lt;br /&gt;
      current_time=Time.new.getutc&lt;br /&gt;
      #get the highest version numbered review&lt;br /&gt;
      next_due_date=@sorted_deadlines[0]&lt;br /&gt;
      #check in which phase the latest review was done.&lt;br /&gt;
      for deadline_version in @sorted_deadlines&lt;br /&gt;
        if (@largest_version_num.created_at &amp;lt; deadline_version.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
      for deadline_time in @sorted_deadlines&lt;br /&gt;
        if (current_time &amp;lt; deadline_time.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    #check if the latest review is done in the current phase.&lt;br /&gt;
    #if latest review is in current phase then edit the latest one.&lt;br /&gt;
    #else create a new version and update it.&lt;br /&gt;
    # editing the latest review&lt;br /&gt;
    if (deadline_version.due_at== deadline_time.due_at)&lt;br /&gt;
      #send it to edit here&lt;br /&gt;
      @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @response = Response.where(map_id: params[:id], version_num:  @largest_version_num.version_num).first&lt;br /&gt;
      @modified_object = @response.response_id&lt;br /&gt;
      @map = @response.map&lt;br /&gt;
      get_content&lt;br /&gt;
      @review_scores = Array.new&lt;br /&gt;
      @questions.each {&lt;br /&gt;
          |question|&lt;br /&gt;
          @review_scores &amp;lt;&amp;lt; Score.where(response_id: @response.response_id, question_id:  question.id).first&lt;br /&gt;
      }&lt;br /&gt;
      #**********************&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
      # Check whether this is Jace's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (check_user_name_jace? &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;)&lt;br /&gt;
          handle_jace_kludge&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
    else&lt;br /&gt;
      #else create a new version and update it.&lt;br /&gt;
      @header = &amp;quot;New&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
      @feedback = params[:feedback]&lt;br /&gt;
      @map = ResponseMap.find(params[:id])&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @modified_object = @map.map_id&lt;br /&gt;
      get_content&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (check_user_name_jace? &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;)&lt;br /&gt;
        handle_jace_kludge&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Creation of a Kludge===&lt;br /&gt;
&lt;br /&gt;
* The rereview method contained a special code to check whether an assignment is “Jace’s assignment”; this was the first assignment that was ever created with a multipart rubric.  It was hard-coded into the system, rather than working on a rubric that was created in the normal way.  It is impossible to remove this code without breaking that assignment. It is now implemented as a separate method named handle_jace_kludge.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
The following code was present in the rereview method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end     &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
We added two methods named 'handle_jace_kludge' and 'check_user_name_jace?'&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def check_user_name_jace?&lt;br /&gt;
    return @assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def handle_jace_kludge&lt;br /&gt;
    # ** if assignment belongs to Jace handle it depending on the assignment id **&lt;br /&gt;
    if @assignment.id &amp;lt; 469&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      render :action =&amp;gt; 'custom_response'&lt;br /&gt;
    else&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Moved methods from Response Controller to appropriate models===&lt;br /&gt;
&lt;br /&gt;
* Sorting review versions is not a controller responsibility; So we moved it to the '''Response model'''. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def self.get_largest_version_number(review_scores)&lt;br /&gt;
    @sorted=@review_scores.sort { |m1, m2| (m1.version_num and m2.version_num) ? m2.version_num &amp;lt;=&amp;gt; m1.version_num : (m1.version_num ? -1 : 1) }&lt;br /&gt;
    @largest_version_num=@sorted[0]&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Similarly, the logic for determining whether a review is current or not(i.e., the review was done during the current assignment phase) is not a controller's responsibility and thus was moved to the '''Response model'''. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 def self.getAllResponseVersions&lt;br /&gt;
    #get all previous versions of responses for the response map.&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.where(map_id: @map.id)&lt;br /&gt;
&lt;br /&gt;
    @prev.each do |element|&lt;br /&gt;
      @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    return @review_scores&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== External Links ==&lt;br /&gt;
&lt;br /&gt;
:1. [http://wikis.lib.ncsu.edu/index.php/Expertiza Expertiza]&lt;br /&gt;
&lt;br /&gt;
:2. [http://152.46.19.211:3000/ VCL Link]&lt;br /&gt;
&lt;br /&gt;
:3. [https://github.com/sjoshi6/expertiza Git repository]&lt;br /&gt;
&lt;br /&gt;
:4. [https://docs.google.com/a/ncsu.edu/document/d/1Z0xjFZu-Zy-xm73YyUVUgFCtfWgRwhN1rZuThoyF-U0/edit Steps to setup Expertiza]&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=90014</id>
		<title>CSC/ECE 517 Fall 2014/oss E1458 sst</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=90014"/>
		<updated>2014-10-27T22:37:24Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: /* Expertiza */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''E1458: Expertiza - Refactoring ResponseController'''&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Expertiza==&lt;br /&gt;
[http://wikis.lib.ncsu.edu/index.php/Expertiza Expertiza] is a peer review based course management system. It supports project submission,team creation, and review of the submitted material  including URLs and wiki pages. Students can manage teammates and can conduct reviews on other's topics and projects.&lt;br /&gt;
Expertiza is an open source project based on Ruby on Rails.&lt;br /&gt;
&lt;br /&gt;
== Background==&lt;br /&gt;
As a part of the OSS project 1 we were expected to refactor the Response Controller of Expertiza. Response Controller is responsible for managing the review versions and finding the latest responses and fetching the review scores. This wiki provides a detailed walk through of our contributions to the  Expertiza project with a focus on refactoring.&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
&lt;br /&gt;
The response controller allows the user to create and edit responses to questionnaires such as performing a review, rating a teammate or giving feedback to a reviewer.&lt;br /&gt;
Our project requirement was to perform the following changes :&lt;br /&gt;
* Perform authorization properly.&lt;br /&gt;
* Remove the duplicated methods.&lt;br /&gt;
* Reduce the complexity of the rereview method.&lt;br /&gt;
* Move the functionality incorporated in the controller, to the model, as it is the model's responsibility to implement this functionality.&lt;br /&gt;
&lt;br /&gt;
==Refactoring carried out==&lt;br /&gt;
&lt;br /&gt;
The following changes have been made in the project, as described in the requirements document.&lt;br /&gt;
&lt;br /&gt;
===Perform Authorization correctly===&lt;br /&gt;
&lt;br /&gt;
* Authorization to perform actions was done incorrectly via the redirect_when_disallowed method. It is supposed to be done through the action_allowed? method at the beginning of the class definition. Different authorizations are required for different operations.&lt;br /&gt;
* For example, someone should be allowed to view a response if they wrote the response, or they are the person or on the team whose work the response is applied to, or if they are an instructor or Teaching Assistant for the class.  The person who wrote a response should be allowed to edit it, but not the person/team who was being reviewed, nor the instructor and neither the Teaching Assistant for the class.&lt;br /&gt;
* Earlier, the authorization was handled by denying incorrect access using the redirect_when_disallowed method, which was a more error-prone way of controlling access.  This method has now been removed, and now the class has an action_allowed? method which does the authorization check and allows the user to perform the action only if he/she has the correct permissions.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
'''redirect_when_disallowed''' Method was used for authorization purposes.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def redirect_when_disallowed(response)&lt;br /&gt;
    # For author feedback, participants need to be able to read feedback submitted by other teammates.&lt;br /&gt;
    # If response is anything but author feedback, only the person who wrote feedback should be able to see it.&lt;br /&gt;
    if response.map.read_attribute(:type) == 'FeedbackResponseMap' &amp;amp;&amp;amp; response.map.assignment.team_assignment?&lt;br /&gt;
      team = response.map.reviewer.team&lt;br /&gt;
      unless team.has_user session[:user]&lt;br /&gt;
        redirect_to '/denied?reason=You are not on the team that wrote this feedback'&lt;br /&gt;
      else&lt;br /&gt;
        return false&lt;br /&gt;
      end&lt;br /&gt;
      response.map.read_attribute(:type)&lt;br /&gt;
    end&lt;br /&gt;
    !current_user_id?(response.map.reviewer.user_id)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
We replaced the '''redirect_when_disallowed''' Method by '''action_allowed?''' Method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def action_allowed?&lt;br /&gt;
    case params[:action]&lt;br /&gt;
      when 'view', 'edit', 'delete', 'rereview', 'update'&lt;br /&gt;
        if response.map.read_attribute(:type) == 'FeedbackResponseMap'&lt;br /&gt;
          team = response.map.reviewer.team&lt;br /&gt;
          if team.has_user session[:user]&lt;br /&gt;
           flag= true&lt;br /&gt;
          else&lt;br /&gt;
            flag=false&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flag=true&lt;br /&gt;
    end&lt;br /&gt;
    return flag&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Removal of redundant methods===&lt;br /&gt;
&lt;br /&gt;
* There were two copies of the '''edit, new_feedback and view methods'''.  The second being the newer one, and, according to the rules for method definition, is the one that is currently in use because the latest version overrides the previous versions. We refactored the code by removing the redundant methods for edit, new_feedback and view.&lt;br /&gt;
&lt;br /&gt;
Edit method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def edit&lt;br /&gt;
    @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
    @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
    @return = params[:return]&lt;br /&gt;
    @response = Response.find(params[:id])&lt;br /&gt;
    return if redirect_when_disallowed(@response)&lt;br /&gt;
&lt;br /&gt;
    @map = @response.map&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map_id==@map.map_id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @sorted=@review_scores.sort { |m1, m2| (m1.version_num and m2.version_num) ? m2.version_num &amp;lt;=&amp;gt; m1.version_num : (m1.version_num ? -1 : 1) }&lt;br /&gt;
      @largest_version_num=@sorted[0]&lt;br /&gt;
    end&lt;br /&gt;
    @response = Response.where(map_id: @map.map_id, version_num:  @largest_version_num.version_num).first&lt;br /&gt;
    @modified_object = @response.response_id&lt;br /&gt;
    get_content&lt;br /&gt;
    @review_scores = Array.new&lt;br /&gt;
    @question_type = Array.new&lt;br /&gt;
    @questions.each do |question|&lt;br /&gt;
      @review_scores &amp;lt;&amp;lt; Score.where(response_id: @response.response_id, question_id:  question.id).first&lt;br /&gt;
      @question_type &amp;lt;&amp;lt; QuestionType.find_by_question_id(question.id)&lt;br /&gt;
    end&lt;br /&gt;
    # Check whether this is a custom rubric&lt;br /&gt;
    if @map.questionnaire.section.eql? &amp;quot;Custom&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;custom_update&amp;quot;&lt;br /&gt;
      render :action =&amp;gt; 'custom_response'&lt;br /&gt;
    else&lt;br /&gt;
      # end of special code (except for the end below, to match the if above)&lt;br /&gt;
      #**********************&lt;br /&gt;
      render :action =&amp;gt; 'response'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
New_feedback method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def new_feedback&lt;br /&gt;
    review = Response.find(params[:id])&lt;br /&gt;
    if review&lt;br /&gt;
      reviewer = AssignmentParticipant.where(user_id: session[:user].id, parent_id:  review.map.assignment.id).first&lt;br /&gt;
      map = FeedbackResponseMap.where(reviewed_object_id: review.id, reviewer_id:  reviewer.id).first&lt;br /&gt;
      if map.nil?&lt;br /&gt;
        map = FeedbackResponseMap.create(:reviewed_object_id =&amp;gt; review.id, :reviewer_id =&amp;gt; reviewer.id, :reviewee_id =&amp;gt; review.map.reviewer.id)&lt;br /&gt;
      end&lt;br /&gt;
      redirect_to :action =&amp;gt; 'new', :id =&amp;gt; map.map_id, :return =&amp;gt; &amp;quot;feedback&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      redirect_to :back&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
View method:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def view&lt;br /&gt;
    @response = Response.find(params[:id])&lt;br /&gt;
    return if redirect_when_disallowed(@response)&lt;br /&gt;
    @map = @response.map&lt;br /&gt;
    get_content&lt;br /&gt;
    @review_scores = Array.new&lt;br /&gt;
    @question_type = Array.new&lt;br /&gt;
    @questions.each do |question|&lt;br /&gt;
      @review_scores &amp;lt;&amp;lt; Score.where(response_id: @map.response_id, question_id:  question.id).first&lt;br /&gt;
      @question_type &amp;lt;&amp;lt; QuestionType.find_by_question_id(question.id)&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Cleaning up of the rereview moethod===&lt;br /&gt;
* The rereview method was 98 lines long. We refactored the code by turning several parts of it into methods. Now the code is '''81''' lines long.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def rereview&lt;br /&gt;
    @map=ResponseMap.find(params[:id])&lt;br /&gt;
    get_content&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    #get all versions and find the latest version&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map.id==@map.map.id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    latestResponseVersion&lt;br /&gt;
    #sort all the available versions in descending order.&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @sorted=@review_scores.sort { |m1, m2| (m1.version_num and m2.version_num) ? m2.version_num &amp;lt;=&amp;gt; m1.version_num : (m1.version_num ? -1 : 1) }&lt;br /&gt;
      @largest_version_num=@sorted[0]&lt;br /&gt;
      @latest_phase=@largest_version_num.created_at&lt;br /&gt;
      due_dates = DueDate.where([&amp;quot;assignment_id = ?&amp;quot;, @assignment.id])&lt;br /&gt;
      @sorted_deadlines=Array.new&lt;br /&gt;
      @sorted_deadlines=due_dates.sort { |m1, m2| (m1.due_at and m2.due_at) ? m1.due_at &amp;lt;=&amp;gt; m2.due_at : (m1.due_at ? -1 : 1) }&lt;br /&gt;
      current_time=Time.new.getutc&lt;br /&gt;
      #get the highest version numbered review&lt;br /&gt;
      next_due_date=@sorted_deadlines[0]&lt;br /&gt;
      #check in which phase the latest review was done.&lt;br /&gt;
      for deadline_version in @sorted_deadlines&lt;br /&gt;
        if (@largest_version_num.created_at &amp;lt; deadline_version.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
      for deadline_time in @sorted_deadlines&lt;br /&gt;
        if (current_time &amp;lt; deadline_time.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    #check if the latest review is done in the current phase.&lt;br /&gt;
    #if latest review is in current phase then edit the latest one.&lt;br /&gt;
    #else create a new version and update it.&lt;br /&gt;
    # editing the latest review&lt;br /&gt;
    if (deadline_version.due_at== deadline_time.due_at)&lt;br /&gt;
      #send it to edit here&lt;br /&gt;
      @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @response = Response.find_by_map_id_and_version_num(params[:id], @largest_version_num.version_num)&lt;br /&gt;
      return if redirect_when_disallowed(@response)&lt;br /&gt;
      @modified_object = @response.response_id&lt;br /&gt;
      @map = @response.map&lt;br /&gt;
      get_content&lt;br /&gt;
      @review_scores = Array.new&lt;br /&gt;
      @questions.each {&lt;br /&gt;
          |question|&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; Score.find_by_response_id_and_question_id(@response.response_id, question.id)&lt;br /&gt;
      }&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    else&lt;br /&gt;
      #else create a new version and update it.&lt;br /&gt;
      @header = &amp;quot;New&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
      @feedback = params[:feedback]&lt;br /&gt;
      @map = ResponseMap.find(params[:id])&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @modified_object = @map.map_id&lt;br /&gt;
      get_content&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def rereview&lt;br /&gt;
   @map=ResponseMap.find(params[:id])&lt;br /&gt;
    get_content&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    #get all versions and find the latest version&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map.id==@map.map.id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    @review_scores=response.getAllResponseVersions&lt;br /&gt;
    #sort all the available versions in descending order.&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @largest_version_num = Response.get_largest_version_number(@review_scores)&lt;br /&gt;
      @latest_phase=@largest_version_num.created_at&lt;br /&gt;
      due_dates = DueDate.where([&amp;quot;assignment_id = ?&amp;quot;, @assignment.id])&lt;br /&gt;
&lt;br /&gt;
      @sorted_deadlines = DueDate.sort_deadlines(due_dates)&lt;br /&gt;
      current_time=Time.new.getutc&lt;br /&gt;
      #get the highest version numbered review&lt;br /&gt;
      next_due_date=@sorted_deadlines[0]&lt;br /&gt;
      #check in which phase the latest review was done.&lt;br /&gt;
      for deadline_version in @sorted_deadlines&lt;br /&gt;
        if (@largest_version_num.created_at &amp;lt; deadline_version.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
      for deadline_time in @sorted_deadlines&lt;br /&gt;
        if (current_time &amp;lt; deadline_time.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    #check if the latest review is done in the current phase.&lt;br /&gt;
    #if latest review is in current phase then edit the latest one.&lt;br /&gt;
    #else create a new version and update it.&lt;br /&gt;
    # editing the latest review&lt;br /&gt;
    if (deadline_version.due_at== deadline_time.due_at)&lt;br /&gt;
      #send it to edit here&lt;br /&gt;
      @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @response = Response.where(map_id: params[:id], version_num:  @largest_version_num.version_num).first&lt;br /&gt;
      @modified_object = @response.response_id&lt;br /&gt;
      @map = @response.map&lt;br /&gt;
      get_content&lt;br /&gt;
      @review_scores = Array.new&lt;br /&gt;
      @questions.each {&lt;br /&gt;
          |question|&lt;br /&gt;
          @review_scores &amp;lt;&amp;lt; Score.where(response_id: @response.response_id, question_id:  question.id).first&lt;br /&gt;
      }&lt;br /&gt;
      #**********************&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
      # Check whether this is Jace's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (check_user_name_jace? &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;)&lt;br /&gt;
          handle_jace_kludge&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
    else&lt;br /&gt;
      #else create a new version and update it.&lt;br /&gt;
      @header = &amp;quot;New&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
      @feedback = params[:feedback]&lt;br /&gt;
      @map = ResponseMap.find(params[:id])&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @modified_object = @map.map_id&lt;br /&gt;
      get_content&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (check_user_name_jace? &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;)&lt;br /&gt;
        handle_jace_kludge&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Creation of a Kludge===&lt;br /&gt;
&lt;br /&gt;
* The rereview method contained a special code to check whether an assignment is “Jace’s assignment”; this was the first assignment that was ever created with a multipart rubric.  It was hard-coded into the system, rather than working on a rubric that was created in the normal way.  It is impossible to remove this code without breaking that assignment. It is now implemented as a separate method named handle_jace_kludge.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
The following code was present in the rereview method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end     &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
We added two methods named 'handle_jace_kludge' and 'check_user_name_jace?'&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def check_user_name_jace?&lt;br /&gt;
    return @assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def handle_jace_kludge&lt;br /&gt;
    # ** if assignment belongs to Jace handle it depending on the assignment id **&lt;br /&gt;
    if @assignment.id &amp;lt; 469&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      render :action =&amp;gt; 'custom_response'&lt;br /&gt;
    else&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Moved methods from Response Controller to appropriate models===&lt;br /&gt;
&lt;br /&gt;
* Sorting review versions is not a controller responsibility; So we moved it to the '''Response model'''. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def self.get_largest_version_number(review_scores)&lt;br /&gt;
    @sorted=@review_scores.sort { |m1, m2| (m1.version_num and m2.version_num) ? m2.version_num &amp;lt;=&amp;gt; m1.version_num : (m1.version_num ? -1 : 1) }&lt;br /&gt;
    @largest_version_num=@sorted[0]&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Similarly, the logic for determining whether a review is current or not(i.e., the review was done during the current assignment phase) is not a controller's responsibility and thus was moved to the '''Response model'''. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 def self.getAllResponseVersions&lt;br /&gt;
    #get all previous versions of responses for the response map.&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.where(map_id: @map.id)&lt;br /&gt;
&lt;br /&gt;
    @prev.each do |element|&lt;br /&gt;
      @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    return @review_scores&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== External Links ==&lt;br /&gt;
&lt;br /&gt;
:1. [http://wikis.lib.ncsu.edu/index.php/Expertiza Expertiza]&lt;br /&gt;
&lt;br /&gt;
:2. [http://152.46.19.211:3000/ VCL Link]&lt;br /&gt;
&lt;br /&gt;
:3. [https://github.com/sjoshi6/expertiza Git repository]&lt;br /&gt;
&lt;br /&gt;
:4. [https://docs.google.com/a/ncsu.edu/document/d/1Z0xjFZu-Zy-xm73YyUVUgFCtfWgRwhN1rZuThoyF-U0/edit Steps to setup Expertiza]&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=89732</id>
		<title>CSC/ECE 517 Fall 2014/oss E1458 sst</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=89732"/>
		<updated>2014-10-27T00:32:10Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring ResponseController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
&lt;br /&gt;
The response controller allows the user to create and edit responses to questionnaires such as performing a review, rating a teammate or giving feedback to a reviewer.&lt;br /&gt;
Our project requirement was to perform the following changes :&lt;br /&gt;
* Perform authorization properly.&lt;br /&gt;
* Remove the duplicated methods.&lt;br /&gt;
* Reduce the complexity of the rereview method.&lt;br /&gt;
* Move the functionality incorporated in the controller, to the model, as it is the models responsibility to implement this functionality.&lt;br /&gt;
&lt;br /&gt;
==Refactoring carried out==&lt;br /&gt;
&lt;br /&gt;
The following changes have been made in the project, as described in the requirements document.&lt;br /&gt;
&lt;br /&gt;
===Perform Authorization correctly===&lt;br /&gt;
&lt;br /&gt;
* Authorization to perform actions was not checked correctly. It is supposed to be done through the action_allowed? method at the beginning of the class definition. Different authorizations are required for different operations. For example, someone should be allowed to view a response if they wrote the response, or they are the person or on the team whose work the response applied to, or if they are an instructor or TA for the class.  The person who wrote a response should be allowed to edit it, but not the person/team who was being reviewed, nor the instructor or TA for the class.&lt;br /&gt;
* Earlier, the authorization was denied by the redirect_when_disallowed method, which was a more error-prone way of controlling access.  This method has now been removed, and now the class has an action_allowed? Method which does the authorization check and allows the user to perform the action if it is allowed.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
'''redirect_when_disallowed''' Method was used for authorization purposes.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def redirect_when_disallowed(response)&lt;br /&gt;
    # For author feedback, participants need to be able to read feedback submitted by other teammates.&lt;br /&gt;
    # If response is anything but author feedback, only the person who wrote feedback should be able to see it.&lt;br /&gt;
    if response.map.read_attribute(:type) == 'FeedbackResponseMap' &amp;amp;&amp;amp; response.map.assignment.team_assignment?&lt;br /&gt;
      team = response.map.reviewer.team&lt;br /&gt;
      unless team.has_user session[:user]&lt;br /&gt;
        redirect_to '/denied?reason=You are not on the team that wrote this feedback'&lt;br /&gt;
      else&lt;br /&gt;
        return false&lt;br /&gt;
      end&lt;br /&gt;
      response.map.read_attribute(:type)&lt;br /&gt;
    end&lt;br /&gt;
    !current_user_id?(response.map.reviewer.user_id)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
We replaced the '''redirect_when_disallowed''' Method by '''action_allowed?''' Method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def action_allowed?&lt;br /&gt;
    case params[:action]&lt;br /&gt;
      when 'view', 'edit', 'delete', 'rereview', 'update'&lt;br /&gt;
        if response.map.read_attribute(:type) == 'FeedbackResponseMap'&lt;br /&gt;
          team = response.map.reviewer.team&lt;br /&gt;
          if team.has_user session[:user]&lt;br /&gt;
           flag= true&lt;br /&gt;
          else&lt;br /&gt;
            flag=false&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flag=true&lt;br /&gt;
    end&lt;br /&gt;
    return flag&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Removal of redundant methods===&lt;br /&gt;
&lt;br /&gt;
* There were two copies of the '''edit, new_feedback and view methods'''.  The second being the newer one, and, according to the rules for method definition, is the one that is currently in use because the latest version overrides the previous versions. We refactored the code by removing the redundant methods for edit, new_feedback and view.&lt;br /&gt;
&lt;br /&gt;
===Cleaning up of the rereview moethod===&lt;br /&gt;
* The rereview method was 98 lines long. We refactored the code by turning several parts of it into methods. Now the code is '''81''' lines long.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def rereview&lt;br /&gt;
    @map=ResponseMap.find(params[:id])&lt;br /&gt;
    get_content&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    #get all versions and find the latest version&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map.id==@map.map.id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    latestResponseVersion&lt;br /&gt;
    #sort all the available versions in descending order.&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @sorted=@review_scores.sort { |m1, m2| (m1.version_num and m2.version_num) ? m2.version_num &amp;lt;=&amp;gt; m1.version_num : (m1.version_num ? -1 : 1) }&lt;br /&gt;
      @largest_version_num=@sorted[0]&lt;br /&gt;
      @latest_phase=@largest_version_num.created_at&lt;br /&gt;
      due_dates = DueDate.where([&amp;quot;assignment_id = ?&amp;quot;, @assignment.id])&lt;br /&gt;
      @sorted_deadlines=Array.new&lt;br /&gt;
      @sorted_deadlines=due_dates.sort { |m1, m2| (m1.due_at and m2.due_at) ? m1.due_at &amp;lt;=&amp;gt; m2.due_at : (m1.due_at ? -1 : 1) }&lt;br /&gt;
      current_time=Time.new.getutc&lt;br /&gt;
      #get the highest version numbered review&lt;br /&gt;
      next_due_date=@sorted_deadlines[0]&lt;br /&gt;
      #check in which phase the latest review was done.&lt;br /&gt;
      for deadline_version in @sorted_deadlines&lt;br /&gt;
        if (@largest_version_num.created_at &amp;lt; deadline_version.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
      for deadline_time in @sorted_deadlines&lt;br /&gt;
        if (current_time &amp;lt; deadline_time.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    #check if the latest review is done in the current phase.&lt;br /&gt;
    #if latest review is in current phase then edit the latest one.&lt;br /&gt;
    #else create a new version and update it.&lt;br /&gt;
    # editing the latest review&lt;br /&gt;
    if (deadline_version.due_at== deadline_time.due_at)&lt;br /&gt;
      #send it to edit here&lt;br /&gt;
      @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @response = Response.find_by_map_id_and_version_num(params[:id], @largest_version_num.version_num)&lt;br /&gt;
      return if redirect_when_disallowed(@response)&lt;br /&gt;
      @modified_object = @response.response_id&lt;br /&gt;
      @map = @response.map&lt;br /&gt;
      get_content&lt;br /&gt;
      @review_scores = Array.new&lt;br /&gt;
      @questions.each {&lt;br /&gt;
          |question|&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; Score.find_by_response_id_and_question_id(@response.response_id, question.id)&lt;br /&gt;
      }&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    else&lt;br /&gt;
      #else create a new version and update it.&lt;br /&gt;
      @header = &amp;quot;New&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
      @feedback = params[:feedback]&lt;br /&gt;
      @map = ResponseMap.find(params[:id])&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @modified_object = @map.map_id&lt;br /&gt;
      get_content&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def rereview&lt;br /&gt;
   @map=ResponseMap.find(params[:id])&lt;br /&gt;
    get_content&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    #get all versions and find the latest version&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map.id==@map.map.id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    @review_scores=response.getAllResponseVersions&lt;br /&gt;
    #sort all the available versions in descending order.&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @largest_version_num = Response.get_largest_version_number(@review_scores)&lt;br /&gt;
      @latest_phase=@largest_version_num.created_at&lt;br /&gt;
      due_dates = DueDate.where([&amp;quot;assignment_id = ?&amp;quot;, @assignment.id])&lt;br /&gt;
&lt;br /&gt;
      @sorted_deadlines = DueDate.sort_deadlines(due_dates)&lt;br /&gt;
      current_time=Time.new.getutc&lt;br /&gt;
      #get the highest version numbered review&lt;br /&gt;
      next_due_date=@sorted_deadlines[0]&lt;br /&gt;
      #check in which phase the latest review was done.&lt;br /&gt;
      for deadline_version in @sorted_deadlines&lt;br /&gt;
        if (@largest_version_num.created_at &amp;lt; deadline_version.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
      for deadline_time in @sorted_deadlines&lt;br /&gt;
        if (current_time &amp;lt; deadline_time.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    #check if the latest review is done in the current phase.&lt;br /&gt;
    #if latest review is in current phase then edit the latest one.&lt;br /&gt;
    #else create a new version and update it.&lt;br /&gt;
    # editing the latest review&lt;br /&gt;
    if (deadline_version.due_at== deadline_time.due_at)&lt;br /&gt;
      #send it to edit here&lt;br /&gt;
      @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @response = Response.where(map_id: params[:id], version_num:  @largest_version_num.version_num).first&lt;br /&gt;
      @modified_object = @response.response_id&lt;br /&gt;
      @map = @response.map&lt;br /&gt;
      get_content&lt;br /&gt;
      @review_scores = Array.new&lt;br /&gt;
      @questions.each {&lt;br /&gt;
          |question|&lt;br /&gt;
          @review_scores &amp;lt;&amp;lt; Score.where(response_id: @response.response_id, question_id:  question.id).first&lt;br /&gt;
      }&lt;br /&gt;
      #**********************&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
      # Check whether this is Jace's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (check_user_name_jace? &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;)&lt;br /&gt;
          handle_jace_kludge&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
    else&lt;br /&gt;
      #else create a new version and update it.&lt;br /&gt;
      @header = &amp;quot;New&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
      @feedback = params[:feedback]&lt;br /&gt;
      @map = ResponseMap.find(params[:id])&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @modified_object = @map.map_id&lt;br /&gt;
      get_content&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (check_user_name_jace? &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;)&lt;br /&gt;
        handle_jace_kludge&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Creation of a Kludge===&lt;br /&gt;
&lt;br /&gt;
* The rereview method contained a special code to check whether an assignment is “Jen’s assignment”; this was the first assignment that was ever created with a multipart rubric.  It was hard-coded into the system, rather than working on a rubric that was created in the normal way.  It is impossible to remove this code without breaking that assignment. It is now implemented as a separate method named handle_jace_kludge.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
The following code was present in the rereview method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end     &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
We added a method named 'handle_jace_kludge'.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def handle_jace_kludge&lt;br /&gt;
    # ** if assignment belongs to Jace handle it depending on the assignment id **&lt;br /&gt;
    if @assignment.id &amp;lt; 469&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      render :action =&amp;gt; 'custom_response'&lt;br /&gt;
    else&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Moved methods from Response Controller to appropriate models===&lt;br /&gt;
&lt;br /&gt;
* Sorting review versions is not a controller responsibility; So we moved it to the '''Response model'''. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 def self.getAllResponseVersions&lt;br /&gt;
    #get all previous versions of responses for the response map.&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.where(map_id: @map.id)&lt;br /&gt;
&lt;br /&gt;
    @prev.each do |element|&lt;br /&gt;
      @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    return @review_scores&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Similarly, the logic for determining whether a review is current or not(i.e., the review was done during the current assignment phase) is not a controller's responsibility and thus was moved to the '''Response model'''. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def self.get_largest_version_number(review_scores)&lt;br /&gt;
    @sorted=@review_scores.sort { |m1, m2| (m1.version_num and m2.version_num) ? m2.version_num &amp;lt;=&amp;gt; m1.version_num : (m1.version_num ? -1 : 1) }&lt;br /&gt;
    @largest_version_num=@sorted[0]&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== External Links ==&lt;br /&gt;
&lt;br /&gt;
:1. [http://wikis.lib.ncsu.edu/index.php/Expertiza Expertiza]&lt;br /&gt;
&lt;br /&gt;
:2. [http://152.7.99.43:3000/ VCL Link]&lt;br /&gt;
&lt;br /&gt;
:3. [https://github.com/nixtish/expertiza Git repository]&lt;br /&gt;
&lt;br /&gt;
:4. [https://docs.google.com/a/ncsu.edu/document/d/1Z0xjFZu-Zy-xm73YyUVUgFCtfWgRwhN1rZuThoyF-U0/edit Steps to setup Expertiza]&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=89730</id>
		<title>CSC/ECE 517 Fall 2014/oss E1458 sst</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=89730"/>
		<updated>2014-10-27T00:22:44Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: /* Perform Authorization correctly */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring ResponseController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
&lt;br /&gt;
The response controller allows the user to create and edit responses to questionnaires such as performing a review, rating a teammate or giving feedback to a reviewer.&lt;br /&gt;
Our project requirement was to perform the following changes :&lt;br /&gt;
* Perform authorization properly.&lt;br /&gt;
* Remove the duplicated methods.&lt;br /&gt;
* Reduce the complexity of the rereview method.&lt;br /&gt;
* Move the functionality incorporated in the controller, to the model, as it is the models responsibility to implement this functionality.&lt;br /&gt;
&lt;br /&gt;
==Refactoring carried out==&lt;br /&gt;
&lt;br /&gt;
The following changes have been made in the project, as described in the requirements document.&lt;br /&gt;
&lt;br /&gt;
===Perform Authorization correctly===&lt;br /&gt;
&lt;br /&gt;
* Authorization to perform actions was not checked correctly. It is supposed to be done through the action_allowed? method at the beginning of the class definition. Different authorizations are required for different operations. For example, someone should be allowed to view a response if they wrote the response, or they are the person or on the team whose work the response applied to, or if they are an instructor or TA for the class.  The person who wrote a response should be allowed to edit it, but not the person/team who was being reviewed, nor the instructor or TA for the class.&lt;br /&gt;
* Earlier, the authorization was denied by the redirect_when_disallowed method, which was a more error-prone way of controlling access.  This method has now been removed, and now the class has an action_allowed? Method which does the authorization check and allows the user to perform the action if it is allowed.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
'''redirect_when_disallowed''' Method was used for authorization purposes.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def redirect_when_disallowed(response)&lt;br /&gt;
    # For author feedback, participants need to be able to read feedback submitted by other teammates.&lt;br /&gt;
    # If response is anything but author feedback, only the person who wrote feedback should be able to see it.&lt;br /&gt;
    if response.map.read_attribute(:type) == 'FeedbackResponseMap' &amp;amp;&amp;amp; response.map.assignment.team_assignment?&lt;br /&gt;
      team = response.map.reviewer.team&lt;br /&gt;
      unless team.has_user session[:user]&lt;br /&gt;
        redirect_to '/denied?reason=You are not on the team that wrote this feedback'&lt;br /&gt;
      else&lt;br /&gt;
        return false&lt;br /&gt;
      end&lt;br /&gt;
      response.map.read_attribute(:type)&lt;br /&gt;
    end&lt;br /&gt;
    !current_user_id?(response.map.reviewer.user_id)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
We replaced the '''redirect_when_disallowed''' Method by '''action_allowed?''' Method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def action_allowed?&lt;br /&gt;
    case params[:action]&lt;br /&gt;
      when 'view', 'edit', 'delete', 'rereview', 'update'&lt;br /&gt;
        if response.map.read_attribute(:type) == 'FeedbackResponseMap'&lt;br /&gt;
          team = response.map.reviewer.team&lt;br /&gt;
          if team.has_user session[:user]&lt;br /&gt;
           flag= true&lt;br /&gt;
          else&lt;br /&gt;
            flag=false&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flag=true&lt;br /&gt;
    end&lt;br /&gt;
    return flag&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Removal of redundant methods===&lt;br /&gt;
&lt;br /&gt;
* There were two copies of the '''edit, new_feedback and view methods'''.  The second being the newer one, and, according to the rules for method definition, is the one that is currently in use because the latest version overrides the previous versions. We refactored the code by removing the redundant methods for edit, new_feedback and view.&lt;br /&gt;
&lt;br /&gt;
===Cleaning up of the rereview moethod===&lt;br /&gt;
* The rereview method was 98 lines long. We refactored the code by turning several parts of it into methods. Now the code is '''81''' lines long.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def rereview&lt;br /&gt;
    @map=ResponseMap.find(params[:id])&lt;br /&gt;
    get_content&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    #get all versions and find the latest version&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map.id==@map.map.id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    latestResponseVersion&lt;br /&gt;
    #sort all the available versions in descending order.&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @sorted=@review_scores.sort { |m1, m2| (m1.version_num and m2.version_num) ? m2.version_num &amp;lt;=&amp;gt; m1.version_num : (m1.version_num ? -1 : 1) }&lt;br /&gt;
      @largest_version_num=@sorted[0]&lt;br /&gt;
      @latest_phase=@largest_version_num.created_at&lt;br /&gt;
      due_dates = DueDate.where([&amp;quot;assignment_id = ?&amp;quot;, @assignment.id])&lt;br /&gt;
      @sorted_deadlines=Array.new&lt;br /&gt;
      @sorted_deadlines=due_dates.sort { |m1, m2| (m1.due_at and m2.due_at) ? m1.due_at &amp;lt;=&amp;gt; m2.due_at : (m1.due_at ? -1 : 1) }&lt;br /&gt;
      current_time=Time.new.getutc&lt;br /&gt;
      #get the highest version numbered review&lt;br /&gt;
      next_due_date=@sorted_deadlines[0]&lt;br /&gt;
      #check in which phase the latest review was done.&lt;br /&gt;
      for deadline_version in @sorted_deadlines&lt;br /&gt;
        if (@largest_version_num.created_at &amp;lt; deadline_version.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
      for deadline_time in @sorted_deadlines&lt;br /&gt;
        if (current_time &amp;lt; deadline_time.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    #check if the latest review is done in the current phase.&lt;br /&gt;
    #if latest review is in current phase then edit the latest one.&lt;br /&gt;
    #else create a new version and update it.&lt;br /&gt;
    # editing the latest review&lt;br /&gt;
    if (deadline_version.due_at== deadline_time.due_at)&lt;br /&gt;
      #send it to edit here&lt;br /&gt;
      @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @response = Response.find_by_map_id_and_version_num(params[:id], @largest_version_num.version_num)&lt;br /&gt;
      return if redirect_when_disallowed(@response)&lt;br /&gt;
      @modified_object = @response.response_id&lt;br /&gt;
      @map = @response.map&lt;br /&gt;
      get_content&lt;br /&gt;
      @review_scores = Array.new&lt;br /&gt;
      @questions.each {&lt;br /&gt;
          |question|&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; Score.find_by_response_id_and_question_id(@response.response_id, question.id)&lt;br /&gt;
      }&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    else&lt;br /&gt;
      #else create a new version and update it.&lt;br /&gt;
      @header = &amp;quot;New&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
      @feedback = params[:feedback]&lt;br /&gt;
      @map = ResponseMap.find(params[:id])&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @modified_object = @map.map_id&lt;br /&gt;
      get_content&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def rereview&lt;br /&gt;
   @map=ResponseMap.find(params[:id])&lt;br /&gt;
    get_content&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    #get all versions and find the latest version&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map.id==@map.map.id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    @review_scores=response.getAllResponseVersions&lt;br /&gt;
    #sort all the available versions in descending order.&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @largest_version_num = Response.get_largest_version_number(@review_scores)&lt;br /&gt;
      @latest_phase=@largest_version_num.created_at&lt;br /&gt;
      due_dates = DueDate.where([&amp;quot;assignment_id = ?&amp;quot;, @assignment.id])&lt;br /&gt;
&lt;br /&gt;
      @sorted_deadlines = DueDate.sort_deadlines(due_dates)&lt;br /&gt;
      current_time=Time.new.getutc&lt;br /&gt;
      #get the highest version numbered review&lt;br /&gt;
      next_due_date=@sorted_deadlines[0]&lt;br /&gt;
      #check in which phase the latest review was done.&lt;br /&gt;
      for deadline_version in @sorted_deadlines&lt;br /&gt;
        if (@largest_version_num.created_at &amp;lt; deadline_version.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
      for deadline_time in @sorted_deadlines&lt;br /&gt;
        if (current_time &amp;lt; deadline_time.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    #check if the latest review is done in the current phase.&lt;br /&gt;
    #if latest review is in current phase then edit the latest one.&lt;br /&gt;
    #else create a new version and update it.&lt;br /&gt;
    # editing the latest review&lt;br /&gt;
    if (deadline_version.due_at== deadline_time.due_at)&lt;br /&gt;
      #send it to edit here&lt;br /&gt;
      @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @response = Response.where(map_id: params[:id], version_num:  @largest_version_num.version_num).first&lt;br /&gt;
      @modified_object = @response.response_id&lt;br /&gt;
      @map = @response.map&lt;br /&gt;
      get_content&lt;br /&gt;
      @review_scores = Array.new&lt;br /&gt;
      @questions.each {&lt;br /&gt;
          |question|&lt;br /&gt;
          @review_scores &amp;lt;&amp;lt; Score.where(response_id: @response.response_id, question_id:  question.id).first&lt;br /&gt;
      }&lt;br /&gt;
      #**********************&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
      # Check whether this is Jace's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (check_user_name_jace? &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;)&lt;br /&gt;
          handle_jace_kludge&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
    else&lt;br /&gt;
      #else create a new version and update it.&lt;br /&gt;
      @header = &amp;quot;New&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
      @feedback = params[:feedback]&lt;br /&gt;
      @map = ResponseMap.find(params[:id])&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @modified_object = @map.map_id&lt;br /&gt;
      get_content&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (check_user_name_jace? &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;)&lt;br /&gt;
        handle_jace_kludge&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Creation of a Kludge===&lt;br /&gt;
&lt;br /&gt;
* The rereview method contained a special code to check whether an assignment is “Jen’s assignment”; this was the first assignment that was ever created with a multipart rubric.  It was hard-coded into the system, rather than working on a rubric that was created in the normal way.  It is impossible to remove this code without breaking that assignment. It is now implemented as a separate method named handle_jace_kludge.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
The following code was present in the rereview method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end     &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
We added a method named 'handle_jace_kludge'.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def handle_jace_kludge&lt;br /&gt;
    # ** if assignment belongs to Jace handle it depending on the assignment id **&lt;br /&gt;
    if @assignment.id &amp;lt; 469&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      render :action =&amp;gt; 'custom_response'&lt;br /&gt;
    else&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Moved methods from Response Controller to appropriate models===&lt;br /&gt;
&lt;br /&gt;
* Sorting review versions is not a controller responsibility; So we moved it to the '''Response model'''. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 def self.getAllResponseVersions&lt;br /&gt;
    #get all previous versions of responses for the response map.&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.where(map_id: @map.id)&lt;br /&gt;
&lt;br /&gt;
    @prev.each do |element|&lt;br /&gt;
      @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    return @review_scores&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Similarly, the logic for determining whether a review is current or not(i.e., the review was done during the current assignment phase) is not a controller's responsibility and thus was moved to the '''Response model'''. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def self.get_largest_version_number(review_scores)&lt;br /&gt;
    @sorted=@review_scores.sort { |m1, m2| (m1.version_num and m2.version_num) ? m2.version_num &amp;lt;=&amp;gt; m1.version_num : (m1.version_num ? -1 : 1) }&lt;br /&gt;
    @largest_version_num=@sorted[0]&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=89729</id>
		<title>CSC/ECE 517 Fall 2014/oss E1458 sst</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=89729"/>
		<updated>2014-10-27T00:22:20Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: /* Perform Authorization correctly */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring ResponseController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
&lt;br /&gt;
The response controller allows the user to create and edit responses to questionnaires such as performing a review, rating a teammate or giving feedback to a reviewer.&lt;br /&gt;
Our project requirement was to perform the following changes :&lt;br /&gt;
* Perform authorization properly.&lt;br /&gt;
* Remove the duplicated methods.&lt;br /&gt;
* Reduce the complexity of the rereview method.&lt;br /&gt;
* Move the functionality incorporated in the controller, to the model, as it is the models responsibility to implement this functionality.&lt;br /&gt;
&lt;br /&gt;
==Refactoring carried out==&lt;br /&gt;
&lt;br /&gt;
The following changes have been made in the project, as described in the requirements document.&lt;br /&gt;
&lt;br /&gt;
===Perform Authorization correctly===&lt;br /&gt;
&lt;br /&gt;
* Authorization to perform actions was not checked correctly. It is supposed to be done through the action_allowed? method at the beginning of the class definition. Different authorizations are required for different operations. For example, someone should be allowed to view a response if they wrote the response, or they are the person or on the team whose work the response applied to, or if they are an instructor or TA for the class.  The person who wrote a response should be allowed to edit it, but not the person/team who was being reviewed, nor the instructor or TA for the class.&lt;br /&gt;
* Earlier, the authorization was denied by the redirect_when_disallowed method, which was a more error-prone way of controlling access.  This method has now been removed, and now the class has an action_allowed? Method which does the authorization check and allows the user to perform the action if it is allowed.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
'''redirect_when_disallowed''' Method was used for authorization purposes.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def redirect_when_disallowed(response)&lt;br /&gt;
    # For author feedback, participants need to be able to read feedback submitted by other teammates.&lt;br /&gt;
    # If response is anything but author feedback, only the person who wrote feedback should be able to see it.&lt;br /&gt;
    if response.map.read_attribute(:type) == 'FeedbackResponseMap' &amp;amp;&amp;amp; response.map.assignment.team_assignment?&lt;br /&gt;
      team = response.map.reviewer.team&lt;br /&gt;
      unless team.has_user session[:user]&lt;br /&gt;
        redirect_to '/denied?reason=You are not on the team that wrote this feedback'&lt;br /&gt;
      else&lt;br /&gt;
        return false&lt;br /&gt;
      end&lt;br /&gt;
      response.map.read_attribute(:type)&lt;br /&gt;
    end&lt;br /&gt;
    !current_user_id?(response.map.reviewer.user_id)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
We replaced the '''redirect_when_disallowed''' Method by '''action_allowed''' Method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def action_allowed?&lt;br /&gt;
    case params[:action]&lt;br /&gt;
      when 'view', 'edit', 'delete', 'rereview', 'update'&lt;br /&gt;
        if response.map.read_attribute(:type) == 'FeedbackResponseMap'&lt;br /&gt;
          team = response.map.reviewer.team&lt;br /&gt;
          if team.has_user session[:user]&lt;br /&gt;
           flag= true&lt;br /&gt;
          else&lt;br /&gt;
            flag=false&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flag=true&lt;br /&gt;
    end&lt;br /&gt;
    return flag&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Removal of redundant methods===&lt;br /&gt;
&lt;br /&gt;
* There were two copies of the '''edit, new_feedback and view methods'''.  The second being the newer one, and, according to the rules for method definition, is the one that is currently in use because the latest version overrides the previous versions. We refactored the code by removing the redundant methods for edit, new_feedback and view.&lt;br /&gt;
&lt;br /&gt;
===Cleaning up of the rereview moethod===&lt;br /&gt;
* The rereview method was 98 lines long. We refactored the code by turning several parts of it into methods. Now the code is '''81''' lines long.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def rereview&lt;br /&gt;
    @map=ResponseMap.find(params[:id])&lt;br /&gt;
    get_content&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    #get all versions and find the latest version&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map.id==@map.map.id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    latestResponseVersion&lt;br /&gt;
    #sort all the available versions in descending order.&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @sorted=@review_scores.sort { |m1, m2| (m1.version_num and m2.version_num) ? m2.version_num &amp;lt;=&amp;gt; m1.version_num : (m1.version_num ? -1 : 1) }&lt;br /&gt;
      @largest_version_num=@sorted[0]&lt;br /&gt;
      @latest_phase=@largest_version_num.created_at&lt;br /&gt;
      due_dates = DueDate.where([&amp;quot;assignment_id = ?&amp;quot;, @assignment.id])&lt;br /&gt;
      @sorted_deadlines=Array.new&lt;br /&gt;
      @sorted_deadlines=due_dates.sort { |m1, m2| (m1.due_at and m2.due_at) ? m1.due_at &amp;lt;=&amp;gt; m2.due_at : (m1.due_at ? -1 : 1) }&lt;br /&gt;
      current_time=Time.new.getutc&lt;br /&gt;
      #get the highest version numbered review&lt;br /&gt;
      next_due_date=@sorted_deadlines[0]&lt;br /&gt;
      #check in which phase the latest review was done.&lt;br /&gt;
      for deadline_version in @sorted_deadlines&lt;br /&gt;
        if (@largest_version_num.created_at &amp;lt; deadline_version.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
      for deadline_time in @sorted_deadlines&lt;br /&gt;
        if (current_time &amp;lt; deadline_time.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    #check if the latest review is done in the current phase.&lt;br /&gt;
    #if latest review is in current phase then edit the latest one.&lt;br /&gt;
    #else create a new version and update it.&lt;br /&gt;
    # editing the latest review&lt;br /&gt;
    if (deadline_version.due_at== deadline_time.due_at)&lt;br /&gt;
      #send it to edit here&lt;br /&gt;
      @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @response = Response.find_by_map_id_and_version_num(params[:id], @largest_version_num.version_num)&lt;br /&gt;
      return if redirect_when_disallowed(@response)&lt;br /&gt;
      @modified_object = @response.response_id&lt;br /&gt;
      @map = @response.map&lt;br /&gt;
      get_content&lt;br /&gt;
      @review_scores = Array.new&lt;br /&gt;
      @questions.each {&lt;br /&gt;
          |question|&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; Score.find_by_response_id_and_question_id(@response.response_id, question.id)&lt;br /&gt;
      }&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    else&lt;br /&gt;
      #else create a new version and update it.&lt;br /&gt;
      @header = &amp;quot;New&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
      @feedback = params[:feedback]&lt;br /&gt;
      @map = ResponseMap.find(params[:id])&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @modified_object = @map.map_id&lt;br /&gt;
      get_content&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def rereview&lt;br /&gt;
   @map=ResponseMap.find(params[:id])&lt;br /&gt;
    get_content&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    #get all versions and find the latest version&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map.id==@map.map.id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    @review_scores=response.getAllResponseVersions&lt;br /&gt;
    #sort all the available versions in descending order.&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @largest_version_num = Response.get_largest_version_number(@review_scores)&lt;br /&gt;
      @latest_phase=@largest_version_num.created_at&lt;br /&gt;
      due_dates = DueDate.where([&amp;quot;assignment_id = ?&amp;quot;, @assignment.id])&lt;br /&gt;
&lt;br /&gt;
      @sorted_deadlines = DueDate.sort_deadlines(due_dates)&lt;br /&gt;
      current_time=Time.new.getutc&lt;br /&gt;
      #get the highest version numbered review&lt;br /&gt;
      next_due_date=@sorted_deadlines[0]&lt;br /&gt;
      #check in which phase the latest review was done.&lt;br /&gt;
      for deadline_version in @sorted_deadlines&lt;br /&gt;
        if (@largest_version_num.created_at &amp;lt; deadline_version.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
      for deadline_time in @sorted_deadlines&lt;br /&gt;
        if (current_time &amp;lt; deadline_time.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    #check if the latest review is done in the current phase.&lt;br /&gt;
    #if latest review is in current phase then edit the latest one.&lt;br /&gt;
    #else create a new version and update it.&lt;br /&gt;
    # editing the latest review&lt;br /&gt;
    if (deadline_version.due_at== deadline_time.due_at)&lt;br /&gt;
      #send it to edit here&lt;br /&gt;
      @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @response = Response.where(map_id: params[:id], version_num:  @largest_version_num.version_num).first&lt;br /&gt;
      @modified_object = @response.response_id&lt;br /&gt;
      @map = @response.map&lt;br /&gt;
      get_content&lt;br /&gt;
      @review_scores = Array.new&lt;br /&gt;
      @questions.each {&lt;br /&gt;
          |question|&lt;br /&gt;
          @review_scores &amp;lt;&amp;lt; Score.where(response_id: @response.response_id, question_id:  question.id).first&lt;br /&gt;
      }&lt;br /&gt;
      #**********************&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
      # Check whether this is Jace's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (check_user_name_jace? &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;)&lt;br /&gt;
          handle_jace_kludge&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
    else&lt;br /&gt;
      #else create a new version and update it.&lt;br /&gt;
      @header = &amp;quot;New&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
      @feedback = params[:feedback]&lt;br /&gt;
      @map = ResponseMap.find(params[:id])&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @modified_object = @map.map_id&lt;br /&gt;
      get_content&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (check_user_name_jace? &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;)&lt;br /&gt;
        handle_jace_kludge&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Creation of a Kludge===&lt;br /&gt;
&lt;br /&gt;
* The rereview method contained a special code to check whether an assignment is “Jen’s assignment”; this was the first assignment that was ever created with a multipart rubric.  It was hard-coded into the system, rather than working on a rubric that was created in the normal way.  It is impossible to remove this code without breaking that assignment. It is now implemented as a separate method named handle_jace_kludge.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
The following code was present in the rereview method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end     &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
We added a method named 'handle_jace_kludge'.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def handle_jace_kludge&lt;br /&gt;
    # ** if assignment belongs to Jace handle it depending on the assignment id **&lt;br /&gt;
    if @assignment.id &amp;lt; 469&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      render :action =&amp;gt; 'custom_response'&lt;br /&gt;
    else&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Moved methods from Response Controller to appropriate models===&lt;br /&gt;
&lt;br /&gt;
* Sorting review versions is not a controller responsibility; So we moved it to the '''Response model'''. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 def self.getAllResponseVersions&lt;br /&gt;
    #get all previous versions of responses for the response map.&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.where(map_id: @map.id)&lt;br /&gt;
&lt;br /&gt;
    @prev.each do |element|&lt;br /&gt;
      @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    return @review_scores&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Similarly, the logic for determining whether a review is current or not(i.e., the review was done during the current assignment phase) is not a controller's responsibility and thus was moved to the '''Response model'''. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def self.get_largest_version_number(review_scores)&lt;br /&gt;
    @sorted=@review_scores.sort { |m1, m2| (m1.version_num and m2.version_num) ? m2.version_num &amp;lt;=&amp;gt; m1.version_num : (m1.version_num ? -1 : 1) }&lt;br /&gt;
    @largest_version_num=@sorted[0]&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=89724</id>
		<title>CSC/ECE 517 Fall 2014/oss E1458 sst</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=89724"/>
		<updated>2014-10-27T00:00:36Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: /* Creation of a Kludge */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring ResponseController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
&lt;br /&gt;
The response controller allows the user to create and edit responses to questionnaires such as performing a review, rating a teammate or giving feedback to a reviewer.&lt;br /&gt;
Our project requirement was to perform the following changes :&lt;br /&gt;
* Perform authorization properly.&lt;br /&gt;
* Remove the duplicated methods.&lt;br /&gt;
* Reduce the complexity of the rereview method.&lt;br /&gt;
* Move the functionality incorporated in the controller, to the model, as it is the models responsibility to implement this functionality.&lt;br /&gt;
&lt;br /&gt;
==Refactoring carried out==&lt;br /&gt;
&lt;br /&gt;
The following changes have been made in the project, as described in the requirements document.&lt;br /&gt;
&lt;br /&gt;
===Perform Authorization correctly===&lt;br /&gt;
&lt;br /&gt;
* Authorization to perform actions was not checked correctly. It is supposed to be done through the action_allowed? method at the beginning of the class definition. Different authorizations are required for different operations. For example, someone should be allowed to view a response if they wrote the response, or they are the person or on the team whose work the response applied to, or if they are an instructor or TA for the class.  The person who wrote a response should be allowed to edit it, but not the person/team who was being reviewed, nor the instructor or TA for the class.&lt;br /&gt;
* Earlier, the authorization was denied by the redirect_when_disallowed method, which was a more error-prone way of controlling access.  This method has now been removed, and now the class has an action_allowed? Method which does the authorization check and allows the user to perform the action if it is allowed.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
redirect_when_disallowed Method was used for authorization purposes.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def redirect_when_disallowed(response)&lt;br /&gt;
    # For author feedback, participants need to be able to read feedback submitted by other teammates.&lt;br /&gt;
    # If response is anything but author feedback, only the person who wrote feedback should be able to see it.&lt;br /&gt;
    if response.map.read_attribute(:type) == 'FeedbackResponseMap' &amp;amp;&amp;amp; response.map.assignment.team_assignment?&lt;br /&gt;
      team = response.map.reviewer.team&lt;br /&gt;
      unless team.has_user session[:user]&lt;br /&gt;
        redirect_to '/denied?reason=You are not on the team that wrote this feedback'&lt;br /&gt;
      else&lt;br /&gt;
        return false&lt;br /&gt;
      end&lt;br /&gt;
      response.map.read_attribute(:type)&lt;br /&gt;
    end&lt;br /&gt;
    !current_user_id?(response.map.reviewer.user_id)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def action_allowed?&lt;br /&gt;
    case params[:action]&lt;br /&gt;
      when 'view', 'edit', 'delete', 'rereview', 'update'&lt;br /&gt;
        if response.map.read_attribute(:type) == 'FeedbackResponseMap'&lt;br /&gt;
          team = response.map.reviewer.team&lt;br /&gt;
          if team.has_user session[:user]&lt;br /&gt;
           flag= true&lt;br /&gt;
          else&lt;br /&gt;
            flag=false&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flag=true&lt;br /&gt;
    end&lt;br /&gt;
    return flag&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Removal of redundant methods===&lt;br /&gt;
&lt;br /&gt;
* There were two copies of the '''edit, new_feedback and view methods'''.  The second being the newer one, and, according to the rules for method definition, is the one that is currently in use because the latest version overrides the previous versions. We refactored the code by removing the redundant methods for edit, new_feedback and view.&lt;br /&gt;
&lt;br /&gt;
===Cleaning up of the rereview moethod===&lt;br /&gt;
* The rereview method was 98 lines long. We refactored the code by turning several parts of it into methods. Now the code is '''81''' lines long.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def rereview&lt;br /&gt;
    @map=ResponseMap.find(params[:id])&lt;br /&gt;
    get_content&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    #get all versions and find the latest version&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map.id==@map.map.id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    latestResponseVersion&lt;br /&gt;
    #sort all the available versions in descending order.&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @sorted=@review_scores.sort { |m1, m2| (m1.version_num and m2.version_num) ? m2.version_num &amp;lt;=&amp;gt; m1.version_num : (m1.version_num ? -1 : 1) }&lt;br /&gt;
      @largest_version_num=@sorted[0]&lt;br /&gt;
      @latest_phase=@largest_version_num.created_at&lt;br /&gt;
      due_dates = DueDate.where([&amp;quot;assignment_id = ?&amp;quot;, @assignment.id])&lt;br /&gt;
      @sorted_deadlines=Array.new&lt;br /&gt;
      @sorted_deadlines=due_dates.sort { |m1, m2| (m1.due_at and m2.due_at) ? m1.due_at &amp;lt;=&amp;gt; m2.due_at : (m1.due_at ? -1 : 1) }&lt;br /&gt;
      current_time=Time.new.getutc&lt;br /&gt;
      #get the highest version numbered review&lt;br /&gt;
      next_due_date=@sorted_deadlines[0]&lt;br /&gt;
      #check in which phase the latest review was done.&lt;br /&gt;
      for deadline_version in @sorted_deadlines&lt;br /&gt;
        if (@largest_version_num.created_at &amp;lt; deadline_version.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
      for deadline_time in @sorted_deadlines&lt;br /&gt;
        if (current_time &amp;lt; deadline_time.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    #check if the latest review is done in the current phase.&lt;br /&gt;
    #if latest review is in current phase then edit the latest one.&lt;br /&gt;
    #else create a new version and update it.&lt;br /&gt;
    # editing the latest review&lt;br /&gt;
    if (deadline_version.due_at== deadline_time.due_at)&lt;br /&gt;
      #send it to edit here&lt;br /&gt;
      @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @response = Response.find_by_map_id_and_version_num(params[:id], @largest_version_num.version_num)&lt;br /&gt;
      return if redirect_when_disallowed(@response)&lt;br /&gt;
      @modified_object = @response.response_id&lt;br /&gt;
      @map = @response.map&lt;br /&gt;
      get_content&lt;br /&gt;
      @review_scores = Array.new&lt;br /&gt;
      @questions.each {&lt;br /&gt;
          |question|&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; Score.find_by_response_id_and_question_id(@response.response_id, question.id)&lt;br /&gt;
      }&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    else&lt;br /&gt;
      #else create a new version and update it.&lt;br /&gt;
      @header = &amp;quot;New&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
      @feedback = params[:feedback]&lt;br /&gt;
      @map = ResponseMap.find(params[:id])&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @modified_object = @map.map_id&lt;br /&gt;
      get_content&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def rereview&lt;br /&gt;
   @map=ResponseMap.find(params[:id])&lt;br /&gt;
    get_content&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    #get all versions and find the latest version&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map.id==@map.map.id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    @review_scores=response.getAllResponseVersions&lt;br /&gt;
    #sort all the available versions in descending order.&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @largest_version_num = Response.get_largest_version_number(@review_scores)&lt;br /&gt;
      @latest_phase=@largest_version_num.created_at&lt;br /&gt;
      due_dates = DueDate.where([&amp;quot;assignment_id = ?&amp;quot;, @assignment.id])&lt;br /&gt;
&lt;br /&gt;
      @sorted_deadlines = DueDate.sort_deadlines(due_dates)&lt;br /&gt;
      current_time=Time.new.getutc&lt;br /&gt;
      #get the highest version numbered review&lt;br /&gt;
      next_due_date=@sorted_deadlines[0]&lt;br /&gt;
      #check in which phase the latest review was done.&lt;br /&gt;
      for deadline_version in @sorted_deadlines&lt;br /&gt;
        if (@largest_version_num.created_at &amp;lt; deadline_version.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
      for deadline_time in @sorted_deadlines&lt;br /&gt;
        if (current_time &amp;lt; deadline_time.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    #check if the latest review is done in the current phase.&lt;br /&gt;
    #if latest review is in current phase then edit the latest one.&lt;br /&gt;
    #else create a new version and update it.&lt;br /&gt;
    # editing the latest review&lt;br /&gt;
    if (deadline_version.due_at== deadline_time.due_at)&lt;br /&gt;
      #send it to edit here&lt;br /&gt;
      @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @response = Response.where(map_id: params[:id], version_num:  @largest_version_num.version_num).first&lt;br /&gt;
      @modified_object = @response.response_id&lt;br /&gt;
      @map = @response.map&lt;br /&gt;
      get_content&lt;br /&gt;
      @review_scores = Array.new&lt;br /&gt;
      @questions.each {&lt;br /&gt;
          |question|&lt;br /&gt;
          @review_scores &amp;lt;&amp;lt; Score.where(response_id: @response.response_id, question_id:  question.id).first&lt;br /&gt;
      }&lt;br /&gt;
      #**********************&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
      # Check whether this is Jace's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (check_user_name_jace? &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;)&lt;br /&gt;
          handle_jace_kludge&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
    else&lt;br /&gt;
      #else create a new version and update it.&lt;br /&gt;
      @header = &amp;quot;New&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
      @feedback = params[:feedback]&lt;br /&gt;
      @map = ResponseMap.find(params[:id])&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @modified_object = @map.map_id&lt;br /&gt;
      get_content&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (check_user_name_jace? &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;)&lt;br /&gt;
        handle_jace_kludge&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Creation of a Kludge===&lt;br /&gt;
&lt;br /&gt;
* The rereview method contained a special code to check whether an assignment is “Jen’s assignment”; this was the first assignment that was ever created with a multipart rubric.  It was hard-coded into the system, rather than working on a rubric that was created in the normal way.  It is impossible to remove this code without breaking that assignment. It is now implemented as a separate method named handle_jace_kludge.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
The following code was present in the rereview method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end     &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
We added a method named 'handle_jace_kludge'.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def handle_jace_kludge&lt;br /&gt;
    # ** if assignment belongs to Jace handle it depending on the assignment id **&lt;br /&gt;
    if @assignment.id &amp;lt; 469&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      render :action =&amp;gt; 'custom_response'&lt;br /&gt;
    else&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Moved methods from Response Controller to appropriate models===&lt;br /&gt;
&lt;br /&gt;
* /*TODO for wiki Sorting review versions is not a controller responsibility; it would be better to do this in a model class (which class?)  Ditto for determining whether a review is current (i.e., was done during the current assignment phase).  This is a query that is made about a review (actually, about a response, which may be a review, author feedback, etc.).  It should be placed in the appropriate model class.*/&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=89722</id>
		<title>CSC/ECE 517 Fall 2014/oss E1458 sst</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=89722"/>
		<updated>2014-10-27T00:00:01Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: /* Creation of a Kludge */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring ResponseController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
&lt;br /&gt;
The response controller allows the user to create and edit responses to questionnaires such as performing a review, rating a teammate or giving feedback to a reviewer.&lt;br /&gt;
Our project requirement was to perform the following changes :&lt;br /&gt;
* Perform authorization properly.&lt;br /&gt;
* Remove the duplicated methods.&lt;br /&gt;
* Reduce the complexity of the rereview method.&lt;br /&gt;
* Move the functionality incorporated in the controller, to the model, as it is the models responsibility to implement this functionality.&lt;br /&gt;
&lt;br /&gt;
==Refactoring carried out==&lt;br /&gt;
&lt;br /&gt;
The following changes have been made in the project, as described in the requirements document.&lt;br /&gt;
&lt;br /&gt;
===Perform Authorization correctly===&lt;br /&gt;
&lt;br /&gt;
* Authorization to perform actions was not checked correctly. It is supposed to be done through the action_allowed? method at the beginning of the class definition. Different authorizations are required for different operations. For example, someone should be allowed to view a response if they wrote the response, or they are the person or on the team whose work the response applied to, or if they are an instructor or TA for the class.  The person who wrote a response should be allowed to edit it, but not the person/team who was being reviewed, nor the instructor or TA for the class.&lt;br /&gt;
* Earlier, the authorization was denied by the redirect_when_disallowed method, which was a more error-prone way of controlling access.  This method has now been removed, and now the class has an action_allowed? Method which does the authorization check and allows the user to perform the action if it is allowed.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
redirect_when_disallowed Method was used for authorization purposes.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def redirect_when_disallowed(response)&lt;br /&gt;
    # For author feedback, participants need to be able to read feedback submitted by other teammates.&lt;br /&gt;
    # If response is anything but author feedback, only the person who wrote feedback should be able to see it.&lt;br /&gt;
    if response.map.read_attribute(:type) == 'FeedbackResponseMap' &amp;amp;&amp;amp; response.map.assignment.team_assignment?&lt;br /&gt;
      team = response.map.reviewer.team&lt;br /&gt;
      unless team.has_user session[:user]&lt;br /&gt;
        redirect_to '/denied?reason=You are not on the team that wrote this feedback'&lt;br /&gt;
      else&lt;br /&gt;
        return false&lt;br /&gt;
      end&lt;br /&gt;
      response.map.read_attribute(:type)&lt;br /&gt;
    end&lt;br /&gt;
    !current_user_id?(response.map.reviewer.user_id)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def action_allowed?&lt;br /&gt;
    case params[:action]&lt;br /&gt;
      when 'view', 'edit', 'delete', 'rereview', 'update'&lt;br /&gt;
        if response.map.read_attribute(:type) == 'FeedbackResponseMap'&lt;br /&gt;
          team = response.map.reviewer.team&lt;br /&gt;
          if team.has_user session[:user]&lt;br /&gt;
           flag= true&lt;br /&gt;
          else&lt;br /&gt;
            flag=false&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flag=true&lt;br /&gt;
    end&lt;br /&gt;
    return flag&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Removal of redundant methods===&lt;br /&gt;
&lt;br /&gt;
* There were two copies of the '''edit, new_feedback and view methods'''.  The second being the newer one, and, according to the rules for method definition, is the one that is currently in use because the latest version overrides the previous versions. We refactored the code by removing the redundant methods for edit, new_feedback and view.&lt;br /&gt;
&lt;br /&gt;
===Cleaning up of the rereview moethod===&lt;br /&gt;
* The rereview method was 98 lines long. We refactored the code by turning several parts of it into methods. Now the code is '''81''' lines long.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def rereview&lt;br /&gt;
    @map=ResponseMap.find(params[:id])&lt;br /&gt;
    get_content&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    #get all versions and find the latest version&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map.id==@map.map.id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    latestResponseVersion&lt;br /&gt;
    #sort all the available versions in descending order.&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @sorted=@review_scores.sort { |m1, m2| (m1.version_num and m2.version_num) ? m2.version_num &amp;lt;=&amp;gt; m1.version_num : (m1.version_num ? -1 : 1) }&lt;br /&gt;
      @largest_version_num=@sorted[0]&lt;br /&gt;
      @latest_phase=@largest_version_num.created_at&lt;br /&gt;
      due_dates = DueDate.where([&amp;quot;assignment_id = ?&amp;quot;, @assignment.id])&lt;br /&gt;
      @sorted_deadlines=Array.new&lt;br /&gt;
      @sorted_deadlines=due_dates.sort { |m1, m2| (m1.due_at and m2.due_at) ? m1.due_at &amp;lt;=&amp;gt; m2.due_at : (m1.due_at ? -1 : 1) }&lt;br /&gt;
      current_time=Time.new.getutc&lt;br /&gt;
      #get the highest version numbered review&lt;br /&gt;
      next_due_date=@sorted_deadlines[0]&lt;br /&gt;
      #check in which phase the latest review was done.&lt;br /&gt;
      for deadline_version in @sorted_deadlines&lt;br /&gt;
        if (@largest_version_num.created_at &amp;lt; deadline_version.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
      for deadline_time in @sorted_deadlines&lt;br /&gt;
        if (current_time &amp;lt; deadline_time.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    #check if the latest review is done in the current phase.&lt;br /&gt;
    #if latest review is in current phase then edit the latest one.&lt;br /&gt;
    #else create a new version and update it.&lt;br /&gt;
    # editing the latest review&lt;br /&gt;
    if (deadline_version.due_at== deadline_time.due_at)&lt;br /&gt;
      #send it to edit here&lt;br /&gt;
      @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @response = Response.find_by_map_id_and_version_num(params[:id], @largest_version_num.version_num)&lt;br /&gt;
      return if redirect_when_disallowed(@response)&lt;br /&gt;
      @modified_object = @response.response_id&lt;br /&gt;
      @map = @response.map&lt;br /&gt;
      get_content&lt;br /&gt;
      @review_scores = Array.new&lt;br /&gt;
      @questions.each {&lt;br /&gt;
          |question|&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; Score.find_by_response_id_and_question_id(@response.response_id, question.id)&lt;br /&gt;
      }&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    else&lt;br /&gt;
      #else create a new version and update it.&lt;br /&gt;
      @header = &amp;quot;New&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
      @feedback = params[:feedback]&lt;br /&gt;
      @map = ResponseMap.find(params[:id])&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @modified_object = @map.map_id&lt;br /&gt;
      get_content&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def rereview&lt;br /&gt;
   @map=ResponseMap.find(params[:id])&lt;br /&gt;
    get_content&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    #get all versions and find the latest version&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map.id==@map.map.id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    @review_scores=response.getAllResponseVersions&lt;br /&gt;
    #sort all the available versions in descending order.&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @largest_version_num = Response.get_largest_version_number(@review_scores)&lt;br /&gt;
      @latest_phase=@largest_version_num.created_at&lt;br /&gt;
      due_dates = DueDate.where([&amp;quot;assignment_id = ?&amp;quot;, @assignment.id])&lt;br /&gt;
&lt;br /&gt;
      @sorted_deadlines = DueDate.sort_deadlines(due_dates)&lt;br /&gt;
      current_time=Time.new.getutc&lt;br /&gt;
      #get the highest version numbered review&lt;br /&gt;
      next_due_date=@sorted_deadlines[0]&lt;br /&gt;
      #check in which phase the latest review was done.&lt;br /&gt;
      for deadline_version in @sorted_deadlines&lt;br /&gt;
        if (@largest_version_num.created_at &amp;lt; deadline_version.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
      for deadline_time in @sorted_deadlines&lt;br /&gt;
        if (current_time &amp;lt; deadline_time.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    #check if the latest review is done in the current phase.&lt;br /&gt;
    #if latest review is in current phase then edit the latest one.&lt;br /&gt;
    #else create a new version and update it.&lt;br /&gt;
    # editing the latest review&lt;br /&gt;
    if (deadline_version.due_at== deadline_time.due_at)&lt;br /&gt;
      #send it to edit here&lt;br /&gt;
      @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @response = Response.where(map_id: params[:id], version_num:  @largest_version_num.version_num).first&lt;br /&gt;
      @modified_object = @response.response_id&lt;br /&gt;
      @map = @response.map&lt;br /&gt;
      get_content&lt;br /&gt;
      @review_scores = Array.new&lt;br /&gt;
      @questions.each {&lt;br /&gt;
          |question|&lt;br /&gt;
          @review_scores &amp;lt;&amp;lt; Score.where(response_id: @response.response_id, question_id:  question.id).first&lt;br /&gt;
      }&lt;br /&gt;
      #**********************&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
      # Check whether this is Jace's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (check_user_name_jace? &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;)&lt;br /&gt;
          handle_jace_kludge&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
    else&lt;br /&gt;
      #else create a new version and update it.&lt;br /&gt;
      @header = &amp;quot;New&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
      @feedback = params[:feedback]&lt;br /&gt;
      @map = ResponseMap.find(params[:id])&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @modified_object = @map.map_id&lt;br /&gt;
      get_content&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (check_user_name_jace? &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;)&lt;br /&gt;
        handle_jace_kludge&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Creation of a Kludge===&lt;br /&gt;
&lt;br /&gt;
* The rereview method contained a special code to check whether an assignment is “Jen’s assignment”; this was the first assignment that was ever created with a multipart rubric.  It was hard-coded into the system, rather than working on a rubric that was created in the normal way.  It is impossible to remove this code without breaking that assignment. It is now implemented as a separate method named handle_jace_kludge.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
The following code was present in the rereview method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end     &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
We added a method named 'handle_jace_kludge'.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def handle_jace_kludge&lt;br /&gt;
    # ** if assignment belongs to Jace handle it depending on the assignment id **&lt;br /&gt;
    if @assignment.id &amp;lt; 469&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      render :action =&amp;gt; 'custom_response'&lt;br /&gt;
    else&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Moved methods from Response Controller to appropriate models===&lt;br /&gt;
&lt;br /&gt;
* /*TODO for wiki Sorting review versions is not a controller responsibility; it would be better to do this in a model class (which class?)  Ditto for determining whether a review is current (i.e., was done during the current assignment phase).  This is a query that is made about a review (actually, about a response, which may be a review, author feedback, etc.).  It should be placed in the appropriate model class.*/&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=89704</id>
		<title>CSC/ECE 517 Fall 2014/oss E1458 sst</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=89704"/>
		<updated>2014-10-26T23:44:26Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring ResponseController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
&lt;br /&gt;
The response controller allows the user to create and edit responses to questionnaires such as performing a review, rating a teammate or giving feedback to a reviewer.&lt;br /&gt;
Our project requirement was to perform the following changes :&lt;br /&gt;
* Perform authorization properly.&lt;br /&gt;
* Remove the duplicated methods.&lt;br /&gt;
* Reduce the complexity of the rereview method.&lt;br /&gt;
* Move the functionality incorporated in the controller, to the model, as it is the models responsibility to implement this functionality.&lt;br /&gt;
&lt;br /&gt;
==Refactoring carried out==&lt;br /&gt;
&lt;br /&gt;
The following changes have been made in the project, as described in the requirements document.&lt;br /&gt;
&lt;br /&gt;
===Perform Authorization correctly===&lt;br /&gt;
&lt;br /&gt;
* Authorization to perform actions was not checked correctly. It is supposed to be done through the action_allowed? method at the beginning of the class definition. Different authorizations are required for different operations. For example, someone should be allowed to view a response if they wrote the response, or they are the person or on the team whose work the response applied to, or if they are an instructor or TA for the class.  The person who wrote a response should be allowed to edit it, but not the person/team who was being reviewed, nor the instructor or TA for the class.&lt;br /&gt;
* Earlier, the authorization was denied by the redirect_when_disallowed method, which was a more error-prone way of controlling access.  This method has now been removed, and now the class has an action_allowed? Method which does the authorization check and allows the user to perform the action if it is allowed.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
redirect_when_disallowed Method was used for authorization purposes.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def redirect_when_disallowed(response)&lt;br /&gt;
    # For author feedback, participants need to be able to read feedback submitted by other teammates.&lt;br /&gt;
    # If response is anything but author feedback, only the person who wrote feedback should be able to see it.&lt;br /&gt;
    if response.map.read_attribute(:type) == 'FeedbackResponseMap' &amp;amp;&amp;amp; response.map.assignment.team_assignment?&lt;br /&gt;
      team = response.map.reviewer.team&lt;br /&gt;
      unless team.has_user session[:user]&lt;br /&gt;
        redirect_to '/denied?reason=You are not on the team that wrote this feedback'&lt;br /&gt;
      else&lt;br /&gt;
        return false&lt;br /&gt;
      end&lt;br /&gt;
      response.map.read_attribute(:type)&lt;br /&gt;
    end&lt;br /&gt;
    !current_user_id?(response.map.reviewer.user_id)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Code snippet&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Removal of redundant methods===&lt;br /&gt;
&lt;br /&gt;
* There were two copies of the '''edit, new_feedback and view methods'''.  The second being the newer one, and, according to the rules for method definition, is the one that is currently in use because the latest version overrides the previous versions. We refactored the code by removing the redundant methods for edit, new_feedback and view.&lt;br /&gt;
&lt;br /&gt;
===Cleaning up of the rereview moethod===&lt;br /&gt;
* The rereview method was 98 lines long. We refactored the code by turning several parts of it into methods. Now the code is ___ lines long.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def rereview&lt;br /&gt;
    @map=ResponseMap.find(params[:id])&lt;br /&gt;
    get_content&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    #get all versions and find the latest version&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map.id==@map.map.id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    latestResponseVersion&lt;br /&gt;
    #sort all the available versions in descending order.&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @sorted=@review_scores.sort { |m1, m2| (m1.version_num and m2.version_num) ? m2.version_num &amp;lt;=&amp;gt; m1.version_num : (m1.version_num ? -1 : 1) }&lt;br /&gt;
      @largest_version_num=@sorted[0]&lt;br /&gt;
      @latest_phase=@largest_version_num.created_at&lt;br /&gt;
      due_dates = DueDate.where([&amp;quot;assignment_id = ?&amp;quot;, @assignment.id])&lt;br /&gt;
      @sorted_deadlines=Array.new&lt;br /&gt;
      @sorted_deadlines=due_dates.sort { |m1, m2| (m1.due_at and m2.due_at) ? m1.due_at &amp;lt;=&amp;gt; m2.due_at : (m1.due_at ? -1 : 1) }&lt;br /&gt;
      current_time=Time.new.getutc&lt;br /&gt;
      #get the highest version numbered review&lt;br /&gt;
      next_due_date=@sorted_deadlines[0]&lt;br /&gt;
      #check in which phase the latest review was done.&lt;br /&gt;
      for deadline_version in @sorted_deadlines&lt;br /&gt;
        if (@largest_version_num.created_at &amp;lt; deadline_version.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
      for deadline_time in @sorted_deadlines&lt;br /&gt;
        if (current_time &amp;lt; deadline_time.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    #check if the latest review is done in the current phase.&lt;br /&gt;
    #if latest review is in current phase then edit the latest one.&lt;br /&gt;
    #else create a new version and update it.&lt;br /&gt;
    # editing the latest review&lt;br /&gt;
    if (deadline_version.due_at== deadline_time.due_at)&lt;br /&gt;
      #send it to edit here&lt;br /&gt;
      @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @response = Response.find_by_map_id_and_version_num(params[:id], @largest_version_num.version_num)&lt;br /&gt;
      return if redirect_when_disallowed(@response)&lt;br /&gt;
      @modified_object = @response.response_id&lt;br /&gt;
      @map = @response.map&lt;br /&gt;
      get_content&lt;br /&gt;
      @review_scores = Array.new&lt;br /&gt;
      @questions.each {&lt;br /&gt;
          |question|&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; Score.find_by_response_id_and_question_id(@response.response_id, question.id)&lt;br /&gt;
      }&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    else&lt;br /&gt;
      #else create a new version and update it.&lt;br /&gt;
      @header = &amp;quot;New&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
      @feedback = params[:feedback]&lt;br /&gt;
      @map = ResponseMap.find(params[:id])&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @modified_object = @map.map_id&lt;br /&gt;
      get_content&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Code snippet&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Creation of a Kludge===&lt;br /&gt;
&lt;br /&gt;
* The rereview method contained a special code to check whether an assignment is “Jen’s assignment”; this was the first assignment that was ever created with a multipart rubric.  It was hard-coded into the system, rather than working on a rubric that was created in the normal way.  It is impossible to remove this code without breaking that assignment. It is now implemented as a separate method named handle_jace_kludge.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
The following code was present in the rereview method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 #**********************&lt;br /&gt;
 # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end     &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
We added a method named 'handle_jace_kludge'.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Code snippet&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Moved methods from Response Controller to appropriate models===&lt;br /&gt;
&lt;br /&gt;
* /*TODO for wiki Sorting review versions is not a controller responsibility; it would be better to do this in a model class (which class?)  Ditto for determining whether a review is current (i.e., was done during the current assignment phase).  This is a query that is made about a review (actually, about a response, which may be a review, author feedback, etc.).  It should be placed in the appropriate model class.*/&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=89702</id>
		<title>CSC/ECE 517 Fall 2014/oss E1458 sst</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=89702"/>
		<updated>2014-10-26T23:40:56Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring ResponseController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
&lt;br /&gt;
The response controller allows the user to create and edit responses to questionnaires such as performing a review, rating a teammate or giving feedback to a reviewer.&lt;br /&gt;
Our project requirement was to perform the following changes :&lt;br /&gt;
* Perform authorization properly.&lt;br /&gt;
* Remove the duplicated methods.&lt;br /&gt;
* Reduce the complexity of the rereview method.&lt;br /&gt;
* Move the functionality incorporated in the controller, to the model, as it is the models responsibility to implement this functionality.&lt;br /&gt;
&lt;br /&gt;
==Refactoring carried out==&lt;br /&gt;
&lt;br /&gt;
The following changes have been made in the project, as described in the requirements document.&lt;br /&gt;
&lt;br /&gt;
===Perform Authorization correctly===&lt;br /&gt;
&lt;br /&gt;
* Authorization to perform actions was not checked correctly. It is supposed to be done through the action_allowed? method at the beginning of the class definition. Different authorizations are required for different operations. For example, someone should be allowed to view a response if they wrote the response, or they are the person or on the team whose work the response applied to, or if they are an instructor or TA for the class.  The person who wrote a response should be allowed to edit it, but not the person/team who was being reviewed, nor the instructor or TA for the class.&lt;br /&gt;
* Earlier, the authorization was denied by the redirect_when_disallowed method, which was a more error-prone way of controlling access.  This method has now been removed, and now the class has an action_allowed? Method which does the authorization check and allows the user to perform the action if it is allowed.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
redirect_when_disallowed Method was used for authorization purposes.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def redirect_when_disallowed(response)&lt;br /&gt;
    # For author feedback, participants need to be able to read feedback submitted by other teammates.&lt;br /&gt;
    # If response is anything but author feedback, only the person who wrote feedback should be able to see it.&lt;br /&gt;
    if response.map.read_attribute(:type) == 'FeedbackResponseMap' &amp;amp;&amp;amp; response.map.assignment.team_assignment?&lt;br /&gt;
      team = response.map.reviewer.team&lt;br /&gt;
      unless team.has_user session[:user]&lt;br /&gt;
        redirect_to '/denied?reason=You are not on the team that wrote this feedback'&lt;br /&gt;
      else&lt;br /&gt;
        return false&lt;br /&gt;
      end&lt;br /&gt;
      response.map.read_attribute(:type)&lt;br /&gt;
    end&lt;br /&gt;
    !current_user_id?(response.map.reviewer.user_id)&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Code snippet&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Removal of redundant methods===&lt;br /&gt;
&lt;br /&gt;
* There were two copies of the edit, new_feedback and view methods.  The second being the newer one, and, according to the rules for method definition, is the one that is currently in use because the latest version overrides the previous versions. We refactored the code by removing the redundant methods for edit, new_feedback and view.&lt;br /&gt;
&lt;br /&gt;
===Cleaning up of the rereview moethod===&lt;br /&gt;
* The rereview method was 98 lines long. We refactored the code by turning several parts of it into methods. Now the code is ___ lines long.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def rereview&lt;br /&gt;
    @map=ResponseMap.find(params[:id])&lt;br /&gt;
    get_content&lt;br /&gt;
    array_not_empty=0&lt;br /&gt;
    @review_scores=Array.new&lt;br /&gt;
    @prev=Response.all&lt;br /&gt;
    #get all versions and find the latest version&lt;br /&gt;
    for element in @prev&lt;br /&gt;
      if (element.map.id==@map.map.id)&lt;br /&gt;
        array_not_empty=1&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; element&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    latestResponseVersion&lt;br /&gt;
    #sort all the available versions in descending order.&lt;br /&gt;
    if @prev.present?&lt;br /&gt;
      @sorted=@review_scores.sort { |m1, m2| (m1.version_num and m2.version_num) ? m2.version_num &amp;lt;=&amp;gt; m1.version_num : (m1.version_num ? -1 : 1) }&lt;br /&gt;
      @largest_version_num=@sorted[0]&lt;br /&gt;
      @latest_phase=@largest_version_num.created_at&lt;br /&gt;
      due_dates = DueDate.where([&amp;quot;assignment_id = ?&amp;quot;, @assignment.id])&lt;br /&gt;
      @sorted_deadlines=Array.new&lt;br /&gt;
      @sorted_deadlines=due_dates.sort { |m1, m2| (m1.due_at and m2.due_at) ? m1.due_at &amp;lt;=&amp;gt; m2.due_at : (m1.due_at ? -1 : 1) }&lt;br /&gt;
      current_time=Time.new.getutc&lt;br /&gt;
      #get the highest version numbered review&lt;br /&gt;
      next_due_date=@sorted_deadlines[0]&lt;br /&gt;
      #check in which phase the latest review was done.&lt;br /&gt;
      for deadline_version in @sorted_deadlines&lt;br /&gt;
        if (@largest_version_num.created_at &amp;lt; deadline_version.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
      for deadline_time in @sorted_deadlines&lt;br /&gt;
        if (current_time &amp;lt; deadline_time.due_at)&lt;br /&gt;
          break&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    #check if the latest review is done in the current phase.&lt;br /&gt;
    #if latest review is in current phase then edit the latest one.&lt;br /&gt;
    #else create a new version and update it.&lt;br /&gt;
    # editing the latest review&lt;br /&gt;
    if (deadline_version.due_at== deadline_time.due_at)&lt;br /&gt;
      #send it to edit here&lt;br /&gt;
      @header = &amp;quot;Edit&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @response = Response.find_by_map_id_and_version_num(params[:id], @largest_version_num.version_num)&lt;br /&gt;
      return if redirect_when_disallowed(@response)&lt;br /&gt;
      @modified_object = @response.response_id&lt;br /&gt;
      @map = @response.map&lt;br /&gt;
      get_content&lt;br /&gt;
      @review_scores = Array.new&lt;br /&gt;
      @questions.each {&lt;br /&gt;
          |question|&lt;br /&gt;
        @review_scores &amp;lt;&amp;lt; Score.find_by_response_id_and_question_id(@response.response_id, question.id)&lt;br /&gt;
      }&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    else&lt;br /&gt;
      #else create a new version and update it.&lt;br /&gt;
      @header = &amp;quot;New&amp;quot;&lt;br /&gt;
      @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
      @feedback = params[:feedback]&lt;br /&gt;
      @map = ResponseMap.find(params[:id])&lt;br /&gt;
      @return = params[:return]&lt;br /&gt;
      @modified_object = @map.map_id&lt;br /&gt;
      get_content&lt;br /&gt;
      #**********************&lt;br /&gt;
      # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;create&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Code snippet&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Creation of a Kludge===&lt;br /&gt;
&lt;br /&gt;
* The rereview method contained a special code to check whether an assignment is “Jen’s assignment”; this was the first assignment that was ever created with a multipart rubric.  It was hard-coded into the system, rather than working on a rubric that was created in the normal way.  It is impossible to remove this code without breaking that assignment. It is now implemented as a separate method named handle_jace_kludge.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
The following code was present in the rereview method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 #**********************&lt;br /&gt;
 # Check whether this is Jen's assgt. &amp;amp; if so, use her rubric&lt;br /&gt;
      if (@assignment.instructor_id == User.find_by_name(&amp;quot;jace_smith&amp;quot;).id) &amp;amp;&amp;amp; @title == &amp;quot;Review&amp;quot;&lt;br /&gt;
        if @assignment.id &amp;lt; 469&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response'&lt;br /&gt;
        else&lt;br /&gt;
          @next_action = &amp;quot;update&amp;quot;&lt;br /&gt;
          render :action =&amp;gt; 'custom_response_2011'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        # end of special code (except for the end below, to match the if above)&lt;br /&gt;
        #**********************&lt;br /&gt;
        render :action =&amp;gt; 'response'&lt;br /&gt;
      end     &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
We added a method named 'handle_jace_kludge'.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Code snippet&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Moved methods from Response Controller to appropriate models===&lt;br /&gt;
&lt;br /&gt;
* /*TODO for wiki Sorting review versions is not a controller responsibility; it would be better to do this in a model class (which class?)  Ditto for determining whether a review is current (i.e., was done during the current assignment phase).  This is a query that is made about a review (actually, about a response, which may be a review, author feedback, etc.).  It should be placed in the appropriate model class.*/&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=89674</id>
		<title>CSC/ECE 517 Fall 2014/oss E1458 sst</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1458_sst&amp;diff=89674"/>
		<updated>2014-10-26T22:42:10Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: Created page with &amp;quot;=Expertiza - Refactoring ResponseController=  __TOC__  ==Project Description==  The response controller allows the user to create and edit responses to questionnaires such as per...&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring ResponseController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
&lt;br /&gt;
The response controller allows the user to create and edit responses to questionnaires such as performing a review, rating a teammate or giving feedback to a reviewer.&lt;br /&gt;
Our project requirement was to perform the following changes :&lt;br /&gt;
* Perform authorization properly.&lt;br /&gt;
* Remove the duplicated methods.&lt;br /&gt;
* Reduce the complexity of the rereview method.&lt;br /&gt;
* Move the functionality incorporated in the controller, to the model, as it is the models responsibility to implement this functionality.&lt;br /&gt;
&lt;br /&gt;
==Refactoring carried out==&lt;br /&gt;
&lt;br /&gt;
The following changes have been made in the project, as described in the requirements document.&lt;br /&gt;
&lt;br /&gt;
===Perform Authorization correctly===&lt;br /&gt;
&lt;br /&gt;
* Authorization to perform actions was not checked correctly. It is supposed to be done through the action_allowed? method at the beginning of the class definition. Different authorizations are required for different operations. For example, someone should be allowed to view a response if they wrote the response, or they are the person or on the team whose work the response applied to, or if they are an instructor or TA for the class.  The person who wrote a response should be allowed to edit it, but not the person/team who was being reviewed, nor the instructor or TA for the class.&lt;br /&gt;
* Earlier, the authorization was denied by the redirect_when_disallowed method, which was a more error-prone way of controlling access.  This method has now been removed, and now the class has an action_allowed? Method which does the authorization check and allows the user to perform the action if it is allowed.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Code snippet&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Code snippet&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Removal of redundant methods===&lt;br /&gt;
&lt;br /&gt;
* There were two copies of the edit, new_feedback and view methods.  The second being the newer one, and, according to the rules for method definition, is the one that is currently in use because the latest version overrides the previous versions. We refactored the code by removing the redundant methods.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Code snippet&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Code snippet&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Cleaning up of the rereview moethod===&lt;br /&gt;
* The rereview method was 98 lines long. We refactored the code by turning several parts of it into methods. Now the code is ___ lines long.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Code snippet&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Code snippet&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Creation of a Kludge===&lt;br /&gt;
&lt;br /&gt;
* The rereview method contained a special code to check whether an assignment is “Jen’s assignment”; this was the first assignment that was ever created with a multipart rubric.  It was hard-coded into the system, rather than working on a rubric that was created in the normal way.  It is impossible to remove this code without breaking that assignment. It is now implemented as a separate method, handle_jace_kludge.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Code snippet&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Code snippet&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Moved methods from Response Controller to appropriate models===&lt;br /&gt;
&lt;br /&gt;
* /*TODO for wiki Sorting review versions is not a controller responsibility; it would be better to do this in a model class (which class?)  Ditto for determining whether a review is current (i.e., was done during the current assignment phase).  This is a query that is made about a review (actually, about a response, which may be a review, author feedback, etc.).  It should be placed in the appropriate model class.*/&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=User_talk:Sdrangne&amp;diff=89667</id>
		<title>User talk:Sdrangne</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=User_talk:Sdrangne&amp;diff=89667"/>
		<updated>2014-10-26T21:52:30Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: Created page with &amp;quot;CSC/ECE 517 Fall 2014/oss E1458 sst&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;CSC/ECE 517 Fall 2014/oss E1458 sst&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88245</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88245"/>
		<updated>2014-09-24T23:57:55Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Object Relation Mapping(ORM, O/RM, and O/R mapping) provides a technique to efficiently access data from a database in the form of objects which are mapped to the database records. This avoids the hassle of writing database specific queries and creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. This wiki concentrates on features, advantages and disadvantages of using ORM, gives a general overview of various ORM frameworks such as Active records, ORM Adapter, Sequel etc. and provides a basic comparison of their features.  &lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Object Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent.&lt;br /&gt;
&lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
 &lt;br /&gt;
==Features&amp;lt;ref&amp;gt;http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk&amp;lt;/ref&amp;gt;== &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
==Advantages&amp;lt;ref&amp;gt;http://www.techopedia.com/definition/24200/object-relational-mapping--orm&amp;lt;/ref&amp;gt;==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
&lt;br /&gt;
=ORM Frameworks=&lt;br /&gt;
&lt;br /&gt;
==Active Records==&lt;br /&gt;
[http://guides.rubyonrails.org/active_record_basics.html Active Record] was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                   	        # is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                              # find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')          # find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)   # find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                             # find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')            # find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)            # find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')             # create a fred&lt;br /&gt;
user_model.destroy(object)                    	# destroy the user object&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
[http://sequel.jeremyevans.net/documentation.html Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharing.&lt;br /&gt;
&lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic eager loading to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB, [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
&lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=Alternative to ORM=&lt;br /&gt;
==NonSQL databases&amp;lt;ref&amp;gt;http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;lt;/ref&amp;gt;==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk CSC/ECE 517 Spring 2013/ch1 1d zk] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
# [http://www.cs.colorado.edu/~kena/classes/5448/f11/lectures/29-orm.pdf ORM - University of Colorado]&lt;br /&gt;
# [http://www.lynda.com/Ruby-Rails-tutorials/Understanding-ActiveRecord-ActiveRelation/139989/159093-4.html Active Record Tutorial]&lt;br /&gt;
# [http://digitalcommons.macalester.edu/context/mathcs_honors/article/1006/type/native/viewcontent/ Research papers on object relational mapping]&lt;br /&gt;
# [http://www.sitepoint.com/top-ruby-frameworks-rails-and-merb-join-forces/ Merb and Rails]&lt;br /&gt;
&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.&lt;br /&gt;
&lt;br /&gt;
=References =&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.jeremyevans.net/documentation.html Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;br /&gt;
&lt;br /&gt;
=Citations=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88235</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88235"/>
		<updated>2014-09-24T23:43:14Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Object-relational_mapping&amp;lt;/ref&amp;gt;==&lt;br /&gt;
Object Relation Mapping(ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Object Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent.&lt;br /&gt;
&lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
 &lt;br /&gt;
==Features&amp;lt;ref&amp;gt;http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk&amp;lt;/ref&amp;gt;== &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
==Advantages&amp;lt;ref&amp;gt;http://www.techopedia.com/definition/24200/object-relational-mapping--orm&amp;lt;/ref&amp;gt;==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
&lt;br /&gt;
=ORM Frameworks=&lt;br /&gt;
&lt;br /&gt;
==Active Records==&lt;br /&gt;
[http://guides.rubyonrails.org/active_record_basics.html Active Record] was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                   	        # is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                              # find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')          # find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)   # find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                             # find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')            # find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)            # find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')             # create a fred&lt;br /&gt;
user_model.destroy(object)                    	# destroy the user object&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
[http://sequel.jeremyevans.net/documentation.html Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharing.&lt;br /&gt;
&lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic eager loading to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB, [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
&lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=Alternative to ORM=&lt;br /&gt;
==NonSQL databases&amp;lt;ref&amp;gt;http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;lt;/ref&amp;gt;==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk CSC/ECE 517 Spring 2013/ch1 1d zk] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
# [http://www.cs.colorado.edu/~kena/classes/5448/f11/lectures/29-orm.pdf ORM - University of Colorado]&lt;br /&gt;
# [http://www.lynda.com/Ruby-Rails-tutorials/Understanding-ActiveRecord-ActiveRelation/139989/159093-4.html Active Record Tutorial]&lt;br /&gt;
# [http://digitalcommons.macalester.edu/context/mathcs_honors/article/1006/type/native/viewcontent/ Research papers on object relational mapping]&lt;br /&gt;
# [http://www.sitepoint.com/top-ruby-frameworks-rails-and-merb-join-forces/ Merb and Rails]&lt;br /&gt;
&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.&lt;br /&gt;
&lt;br /&gt;
=References =&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.jeremyevans.net/documentation.html Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;br /&gt;
&lt;br /&gt;
=Citations=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88233</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88233"/>
		<updated>2014-09-24T23:41:07Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Object-relational_mapping&amp;lt;/ref&amp;gt;==&lt;br /&gt;
Object Relation Mapping(ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Object Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent.&lt;br /&gt;
&lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
 &lt;br /&gt;
==Features&amp;lt;ref&amp;gt;http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk&amp;lt;/ref&amp;gt;== &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
==Advantages&amp;lt;ref&amp;gt;http://www.techopedia.com/definition/24200/object-relational-mapping--orm&amp;lt;/ref&amp;gt;==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
&lt;br /&gt;
=ORM Frameworks=&lt;br /&gt;
&lt;br /&gt;
==Active Records==&lt;br /&gt;
[http://guides.rubyonrails.org/active_record_basics.html Active Record] was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                   	        # is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                              # find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')          # find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)   # find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                             # find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')            # find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)            # find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')             # create a fred&lt;br /&gt;
user_model.destroy(object)                    	# destroy the user object&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
[http://sequel.jeremyevans.net/documentation.html Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharing.&lt;br /&gt;
&lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic eager loading to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB, [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
&lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=Alternative to ORM=&lt;br /&gt;
==NonSQL databases&amp;lt;ref&amp;gt;http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2013/ch1_1w43_av&amp;lt;/ref&amp;gt;==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk CSC/ECE 517 Spring 2013/ch1 1d zk] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
# [http://www.cs.colorado.edu/~kena/classes/5448/f11/lectures/29-orm.pdf ORM - University of Colorado]&lt;br /&gt;
# [http://www.lynda.com/Ruby-Rails-tutorials/Understanding-ActiveRecord-ActiveRelation/139989/159093-4.html Active Record Tutorial]&lt;br /&gt;
# [http://digitalcommons.macalester.edu/context/mathcs_honors/article/1006/type/native/viewcontent/ Research papers on object relational mapping]&lt;br /&gt;
# [http://www.sitepoint.com/top-ruby-frameworks-rails-and-merb-join-forces/ Merb and Rails]&lt;br /&gt;
&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.&lt;br /&gt;
&lt;br /&gt;
=References =&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.jeremyevans.net/documentation.html Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;br /&gt;
&lt;br /&gt;
=Citations=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88223</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88223"/>
		<updated>2014-09-24T23:30:09Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping&amp;lt;/ref&amp;gt;==&lt;br /&gt;
Object Relation Mapping(ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Object Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent.&lt;br /&gt;
&lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
 &lt;br /&gt;
==Features&amp;lt;ref&amp;gt;http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk&amp;lt;/ref&amp;gt;== &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
==Advantages&amp;lt;ref&amp;gt;http://www.techopedia.com/definition/24200/object-relational-mapping--orm&amp;lt;/ref&amp;gt;==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
&lt;br /&gt;
=ORM Frameworks=&lt;br /&gt;
&lt;br /&gt;
==Active Records&amp;lt;ref&amp;gt;http://guides.rubyonrails.org/active_record_basics.html&amp;lt;/ref&amp;gt;==&lt;br /&gt;
Active Record was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                   	        # is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                              # find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')          # find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)   # find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                             # find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')            # find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)            # find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')             # create a fred&lt;br /&gt;
user_model.destroy(object)                    	# destroy the user object&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
[http://sequel.jeremyevans.net/documentation.html Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
&lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic eager loading to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB, [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
&lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=Alternative to ORM=&lt;br /&gt;
==NonSQL databases==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk CSC/ECE 517 Spring 2013/ch1 1d zk] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
# [http://www.cs.colorado.edu/~kena/classes/5448/f11/lectures/29-orm.pdf ORM - University of Colorado]&lt;br /&gt;
# [http://www.lynda.com/Ruby-Rails-tutorials/Understanding-ActiveRecord-ActiveRelation/139989/159093-4.html Active Record Tutorial]&lt;br /&gt;
# [http://digitalcommons.macalester.edu/context/mathcs_honors/article/1006/type/native/viewcontent/ Research papers on object relational mapping]&lt;br /&gt;
# [http://www.sitepoint.com/top-ruby-frameworks-rails-and-merb-join-forces/ Merb and Rails]&lt;br /&gt;
&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.&lt;br /&gt;
&lt;br /&gt;
=References =&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.jeremyevans.net/documentation.html Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;br /&gt;
&lt;br /&gt;
=Citations=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88222</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88222"/>
		<updated>2014-09-24T23:29:36Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Object Relational Mapping'''&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping&amp;lt;/ref&amp;gt;==&lt;br /&gt;
Object Relation Mapping(ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Object Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent.&lt;br /&gt;
&lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
 &lt;br /&gt;
==Features&amp;lt;ref&amp;gt;http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk&amp;lt;/ref&amp;gt;== &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
==Advantages&amp;lt;ref&amp;gt;http://www.techopedia.com/definition/24200/object-relational-mapping--orm&amp;lt;/ref&amp;gt;==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
&lt;br /&gt;
=ORM Frameworks=&lt;br /&gt;
&lt;br /&gt;
==Active Records&amp;lt;ref&amp;gt;http://guides.rubyonrails.org/active_record_basics.html&amp;lt;/ref&amp;gt;==&lt;br /&gt;
Active Record was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                   	        # is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                              # find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')          # find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)   # find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                             # find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')            # find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)            # find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')             # create a fred&lt;br /&gt;
user_model.destroy(object)                    	# destroy the user object&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
[http://sequel.jeremyevans.net/documentation.html Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
&lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic eager loading to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB, [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
&lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=Alternative to ORM=&lt;br /&gt;
==NonSQL databases==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk CSC/ECE 517 Spring 2013/ch1 1d zk] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
# [http://www.cs.colorado.edu/~kena/classes/5448/f11/lectures/29-orm.pdf ORM - University of Colorado]&lt;br /&gt;
# [http://www.lynda.com/Ruby-Rails-tutorials/Understanding-ActiveRecord-ActiveRelation/139989/159093-4.html Active Record Tutorial]&lt;br /&gt;
# [http://digitalcommons.macalester.edu/context/mathcs_honors/article/1006/type/native/viewcontent/ Research papers on object relational mapping]&lt;br /&gt;
# [http://www.sitepoint.com/top-ruby-frameworks-rails-and-merb-join-forces/ Merb and Rails]&lt;br /&gt;
&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.&lt;br /&gt;
&lt;br /&gt;
=References =&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.jeremyevans.net/documentation.html Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;br /&gt;
&lt;br /&gt;
=Citations=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88220</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88220"/>
		<updated>2014-09-24T23:28:30Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Object Relational Mapping&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping&amp;lt;/ref&amp;gt;==&lt;br /&gt;
Object Relation Mapping(ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Object Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent.&lt;br /&gt;
&lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
 &lt;br /&gt;
==Features&amp;lt;ref&amp;gt;http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk&amp;lt;/ref&amp;gt;== &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
==Advantages&amp;lt;ref&amp;gt;http://www.techopedia.com/definition/24200/object-relational-mapping--orm&amp;lt;/ref&amp;gt;==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
&lt;br /&gt;
=ORM Frameworks=&lt;br /&gt;
&lt;br /&gt;
==Active Records==&lt;br /&gt;
[http://guides.rubyonrails.org/active_record_basics.html Active Record] was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                   	        # is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                              # find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')          # find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)   # find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                             # find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')            # find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)            # find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')             # create a fred&lt;br /&gt;
user_model.destroy(object)                    	# destroy the user object&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
[http://sequel.jeremyevans.net/documentation.html Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
&lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic eager loading to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB, [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
&lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=Alternative to ORM=&lt;br /&gt;
==NonSQL databases==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk CSC/ECE 517 Spring 2013/ch1 1d zk] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
# [http://www.cs.colorado.edu/~kena/classes/5448/f11/lectures/29-orm.pdf ORM - University of Colorado]&lt;br /&gt;
# [http://www.lynda.com/Ruby-Rails-tutorials/Understanding-ActiveRecord-ActiveRelation/139989/159093-4.html Active Record Tutorial]&lt;br /&gt;
# [http://digitalcommons.macalester.edu/context/mathcs_honors/article/1006/type/native/viewcontent/ Research papers on object relational mapping]&lt;br /&gt;
# [http://www.sitepoint.com/top-ruby-frameworks-rails-and-merb-join-forces/ Merb and Rails]&lt;br /&gt;
&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.&lt;br /&gt;
&lt;br /&gt;
=References =&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.jeremyevans.net/documentation.html Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;br /&gt;
&lt;br /&gt;
=Citations=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88218</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88218"/>
		<updated>2014-09-24T23:27:08Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__TOC__&lt;br /&gt;
&lt;br /&gt;
=Object Relational Mapping=&lt;br /&gt;
==Introduction&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping&amp;lt;/ref&amp;gt;==&lt;br /&gt;
Object Relation Mapping(ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Object Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent.&lt;br /&gt;
&lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
 &lt;br /&gt;
==Features&amp;lt;ref&amp;gt;http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk&amp;lt;/ref&amp;gt;== &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
==Advantages&amp;lt;ref&amp;gt;http://www.techopedia.com/definition/24200/object-relational-mapping--orm&amp;lt;/ref&amp;gt;==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages&amp;lt;ref&amp;gt;http://www.techopedia.com/definition/24200/object-relational-mapping--orm&amp;lt;/ref&amp;gt;==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
&lt;br /&gt;
=ORM Frameworks=&lt;br /&gt;
&lt;br /&gt;
==Active Records==&lt;br /&gt;
[http://guides.rubyonrails.org/active_record_basics.html Active Record] was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                   	        # is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                              # find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')          # find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)   # find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                             # find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')            # find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)            # find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')             # create a fred&lt;br /&gt;
user_model.destroy(object)                    	# destroy the user object&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
[http://sequel.jeremyevans.net/documentation.html Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
&lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic eager loading to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB, [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
&lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=Alternative to ORM=&lt;br /&gt;
==NonSQL databases==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk CSC/ECE 517 Spring 2013/ch1 1d zk] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
# [http://www.cs.colorado.edu/~kena/classes/5448/f11/lectures/29-orm.pdf ORM - University of Colorado]&lt;br /&gt;
# [http://www.lynda.com/Ruby-Rails-tutorials/Understanding-ActiveRecord-ActiveRelation/139989/159093-4.html Active Record Tutorial]&lt;br /&gt;
# [http://digitalcommons.macalester.edu/context/mathcs_honors/article/1006/type/native/viewcontent/ Research papers on object relational mapping]&lt;br /&gt;
# [http://www.sitepoint.com/top-ruby-frameworks-rails-and-merb-join-forces/ Merb and Rails]&lt;br /&gt;
&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.&lt;br /&gt;
&lt;br /&gt;
=References =&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.jeremyevans.net/documentation.html Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;br /&gt;
&lt;br /&gt;
=Citations=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88213</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88213"/>
		<updated>2014-09-24T23:20:43Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping] (ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Object Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent.&lt;br /&gt;
&lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
 &lt;br /&gt;
==Features== &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
 &lt;br /&gt;
==Advantages&amp;lt;ref&amp;gt;http://www.techopedia.com/definition/24200/object-relational-mapping--orm&amp;lt;/ref&amp;gt;==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages&amp;lt;ref&amp;gt;http://www.techopedia.com/definition/24200/object-relational-mapping--orm&amp;lt;/ref&amp;gt;==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
&lt;br /&gt;
=ORM Frameworks=&lt;br /&gt;
&lt;br /&gt;
==Active Records==&lt;br /&gt;
[http://guides.rubyonrails.org/active_record_basics.html Active Record] was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                   	        # is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                              # find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')          # find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)   # find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                             # find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')            # find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)            # find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')             # create a fred&lt;br /&gt;
user_model.destroy(object)                    	# destroy the user object&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
[http://sequel.jeremyevans.net/documentation.html Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
&lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic eager loading to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB, [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
&lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=Alternative to ORM=&lt;br /&gt;
==NonSQL databases==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk CSC/ECE 517 Spring 2013/ch1 1d zk] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
# [http://www.cs.colorado.edu/~kena/classes/5448/f11/lectures/29-orm.pdf ORM - University of Colorado]&lt;br /&gt;
# [http://www.lynda.com/Ruby-Rails-tutorials/Understanding-ActiveRecord-ActiveRelation/139989/159093-4.html Active Record Tutorial]&lt;br /&gt;
# [http://digitalcommons.macalester.edu/context/mathcs_honors/article/1006/type/native/viewcontent/ Research papers on object relational mapping]&lt;br /&gt;
# [http://www.sitepoint.com/top-ruby-frameworks-rails-and-merb-join-forces/ Merb and Rails]&lt;br /&gt;
&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.&lt;br /&gt;
&lt;br /&gt;
=References =&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.jeremyevans.net/documentation.html Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;br /&gt;
&lt;br /&gt;
=Citations=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88198</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88198"/>
		<updated>2014-09-24T23:04:42Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping] (ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Object Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent.&lt;br /&gt;
&lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
 &lt;br /&gt;
==Features== &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
 &lt;br /&gt;
==Advantages ==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages ==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
&lt;br /&gt;
=ORM Frameworks=&lt;br /&gt;
&lt;br /&gt;
==Active Records==&lt;br /&gt;
[http://guides.rubyonrails.org/active_record_basics.html Active Record] was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                   	        # is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                              # find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')          # find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)   # find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                             # find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')            # find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)            # find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')             # create a fred&lt;br /&gt;
user_model.destroy(object)                    	# destroy the user object&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
[http://sequel.jeremyevans.net/documentation.html Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
&lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic eager loading to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB, [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
&lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=Alternative to ORM=&lt;br /&gt;
==NonSQL databases==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk CSC/ECE 517 Spring 2013/ch1 1d zk] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
# [http://www.cs.colorado.edu/~kena/classes/5448/f11/lectures/29-orm.pdf ORM - University of Colorado]&lt;br /&gt;
# [http://www.lynda.com/Ruby-Rails-tutorials/Understanding-ActiveRecord-ActiveRelation/139989/159093-4.html Active Record Tutorial]&lt;br /&gt;
# [http://digitalcommons.macalester.edu/context/mathcs_honors/article/1006/type/native/viewcontent/ Research papers on object relational mapping]&lt;br /&gt;
&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.&lt;br /&gt;
&lt;br /&gt;
=References =&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.jeremyevans.net/documentation.html Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88196</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88196"/>
		<updated>2014-09-24T22:57:33Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping] (ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Object Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent.&lt;br /&gt;
&lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
 &lt;br /&gt;
==Features== &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
 &lt;br /&gt;
==Advantages ==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages ==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
&lt;br /&gt;
=ORM Frameworks=&lt;br /&gt;
&lt;br /&gt;
==Active Records==&lt;br /&gt;
[http://guides.rubyonrails.org/active_record_basics.html Active Record] was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                   	        # is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                              # find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')          # find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)   # find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                             # find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')            # find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)            # find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')             # create a fred&lt;br /&gt;
user_model.destroy(object)                    	# destroy the user object&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
[http://sequel.jeremyevans.net/documentation.html Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
&lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic eager loading to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB, [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
&lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=Alternative to ORM=&lt;br /&gt;
==NonSQL databases==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk CSC/ECE 517 Spring 2013/ch1 1d zk] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
# [http://www.cs.colorado.edu/~kena/classes/5448/f11/lectures/29-orm.pdf ORM - University of Colorado]&lt;br /&gt;
&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.&lt;br /&gt;
&lt;br /&gt;
=References =&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.jeremyevans.net/documentation.html Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://sequel.jeremyevans.net/rdoc/classes/Sequel/ThreadedConnectionPool.html Connection Pooling]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=86421</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=86421"/>
		<updated>2014-09-18T04:05:20Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Object Relational Mapping==&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping] (ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Onject Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent.&lt;br /&gt;
&lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
 &lt;br /&gt;
==Features== &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
 &lt;br /&gt;
==Advantages ==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages ==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
&lt;br /&gt;
==Active Records==&lt;br /&gt;
[http://guides.rubyonrails.org/active_record_basics.html Active Record] was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                   	        # is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                              # find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')          # find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)   # find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                             # find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')            # find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)            # find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')             # create a fred&lt;br /&gt;
user_model.destroy(object)                    	# destroy the user object&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
[http://sequel.jeremyevans.net/documentation.html Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* Connection Pooling&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
&lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic eager loading to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB, [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
&lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==NonSQL databases==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
==Comparison of ORM Features==&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
==Further Reading==&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk CSC/ECE 517 Spring 2013/ch1 1d zk] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
&lt;br /&gt;
==Future Work==&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.&lt;br /&gt;
&lt;br /&gt;
==References ==&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.jeremyevans.net/documentation.html Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=86418</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=86418"/>
		<updated>2014-09-18T04:03:55Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Object Relational Mapping==&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping] (ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Onject Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent.&lt;br /&gt;
&lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
 &lt;br /&gt;
==Features== &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
 &lt;br /&gt;
==Advantages ==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages ==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
&lt;br /&gt;
==Active Records==&lt;br /&gt;
[http://guides.rubyonrails.org/active_record_basics.html Active Record] was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                   	        # is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                              # find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')          # find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)   # find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                             # find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')            # find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)            # find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')             # create a fred&lt;br /&gt;
user_model.destroy(object)                    	# destroy the user object&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* Connection Pooling&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
&lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic eager loading to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB, [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
&lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==NonSQL databases==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
==Comparison of ORM Features==&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
==Further Reading==&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk CSC/ECE 517 Spring 2013/ch1 1d zk] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
&lt;br /&gt;
==Future Work==&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.&lt;br /&gt;
&lt;br /&gt;
==References ==&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.jeremyevans.net/documentation.html Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=86368</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=86368"/>
		<updated>2014-09-18T03:36:06Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Object Relational Mapping==&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping] (ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Onject Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attribute attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent. &lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
&lt;br /&gt;
==Advantages ==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages ==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
 &lt;br /&gt;
==Features==&lt;br /&gt;
 &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
 &lt;br /&gt;
==Active Records==&lt;br /&gt;
[http://guides.rubyonrails.org/active_record_basics.html Active Record] was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                                                                  	# is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                                                    	# find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')                             	# find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)&lt;br /&gt;
# find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                                                   	# find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')                 	# find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)               	# find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')                 	# create a fred&lt;br /&gt;
user_model.destroy(object)                                  	# destroy the user object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* Connection Pooling&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading eager loading]to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as [http://github.com/kabari/dm-couchdb-adapter/tree/master CouchDB], [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==NonSQL databases==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Comparison of ORM Features==&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
==Further Reading==&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk CSC/ECE 517 Spring 2013/ch1 1d zk] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
&lt;br /&gt;
==Future Work==&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==References ==&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.rubyforge.org Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=86363</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=86363"/>
		<updated>2014-09-18T03:34:48Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Object Relational Mapping==&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping] (ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Onject Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attribute attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent. &lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
&lt;br /&gt;
==Advantages ==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages ==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
 &lt;br /&gt;
==Features==&lt;br /&gt;
 &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
 &lt;br /&gt;
==Active Records==&lt;br /&gt;
[http://guides.rubyonrails.org/active_record_basics.html Active Record] was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                                                                  	# is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                                                    	# find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')                             	# find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)&lt;br /&gt;
# find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                                                   	# find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')                 	# find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)               	# find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')                 	# create a fred&lt;br /&gt;
user_model.destroy(object)                                  	# destroy the user object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* Connection Pooling&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading eager loading]to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as [http://github.com/kabari/dm-couchdb-adapter/tree/master CouchDB], [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==NonSQL databases==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Comparison of ORM Features==&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
==Further Reading==&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk CSC/ECE 517 Spring 2013/ch1 1d zk] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
&lt;br /&gt;
==Future Work==&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==References ==&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.rubyforge.org Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=86361</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=86361"/>
		<updated>2014-09-18T03:34:03Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Object Relational Mapping==&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping] (ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Onject Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attribute attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent. &lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
&lt;br /&gt;
==Advantages ==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages ==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
 &lt;br /&gt;
==Features==&lt;br /&gt;
 &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
 &lt;br /&gt;
==Active Records==&lt;br /&gt;
[http://guides.rubyonrails.org/active_record_basics.html Active Record] was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                                                                  	# is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                                                    	# find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')                             	# find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)&lt;br /&gt;
# find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                                                   	# find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')                 	# find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)               	# find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')                 	# create a fred&lt;br /&gt;
user_model.destroy(object)                                  	# destroy the user object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* Connection Pooling&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading eager loading]to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as [http://github.com/kabari/dm-couchdb-adapter/tree/master CouchDB], [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==NonSQL databases==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Comparison of ORM Features==&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
==Further Reading==&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk CSC/ECE 517 Spring 2013/ch1 1d zk] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
&lt;br /&gt;
==Future Work==&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==References ==&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.rubyforge.org Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=86353</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=86353"/>
		<updated>2014-09-18T03:32:25Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping] (ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Onject Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attribute attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent. &lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
&lt;br /&gt;
==Advantages ==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages ==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
 &lt;br /&gt;
==Features==&lt;br /&gt;
 &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
 &lt;br /&gt;
==Active Records==&lt;br /&gt;
[http://guides.rubyonrails.org/active_record_basics.html Active Record] was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                                                                  	# is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                                                    	# find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')                             	# find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)&lt;br /&gt;
# find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                                                   	# find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')                 	# find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)               	# find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')                 	# create a fred&lt;br /&gt;
user_model.destroy(object)                                  	# destroy the user object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* Connection Pooling&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading eager loading]to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as [http://github.com/kabari/dm-couchdb-adapter/tree/master CouchDB], [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==NonSQL databases==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Comparison of ORM Features==&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk CSC/ECE 517 Spring 2013/ch1 1d zk] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==References ==&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.rubyforge.org Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=86332</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=86332"/>
		<updated>2014-09-18T03:24:15Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: Created page with &amp;quot;==Introduction== [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping] (ORM, O/RM, and O/R mapping) in computer science is a programming technique fo...&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping] (ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Onject Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attribute attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent. &lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
&lt;br /&gt;
==Advantages ==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages ==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
 &lt;br /&gt;
==Features==&lt;br /&gt;
 &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
 &lt;br /&gt;
==Active Records==&lt;br /&gt;
[http://guides.rubyonrails.org/active_record_basics.html Active Record] was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                                                                  	# is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                                                    	# find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')                             	# find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)&lt;br /&gt;
# find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                                                   	# find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')                 	# find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)               	# find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')                 	# create a fred&lt;br /&gt;
user_model.destroy(object)                                  	# destroy the user object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* Connection Pooling&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading eager loading]to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as [http://github.com/kabari/dm-couchdb-adapter/tree/master CouchDB], [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==NonSQL databases==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Comparison of ORM Features==&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==References ==&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.rubyforge.org Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=User:Sdrangne&amp;diff=86260</id>
		<title>User:Sdrangne</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=User:Sdrangne&amp;diff=86260"/>
		<updated>2014-09-18T01:33:37Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: moved User:Sdrangne to CSC/ECE 517 Fall 2014/ch1a 25 sk&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;#REDIRECT [[CSC/ECE 517 Fall 2014/ch1a 25 sk]]&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_sk&amp;diff=86259</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 sk</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_sk&amp;diff=86259"/>
		<updated>2014-09-18T01:33:37Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: moved User:Sdrangne to CSC/ECE 517 Fall 2014/ch1a 25 sk&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Object Relational Mapping==&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping] (ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Onject Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attribute attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent. &lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
&lt;br /&gt;
==Advantages ==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages ==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
 &lt;br /&gt;
==Features==&lt;br /&gt;
 &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
 &lt;br /&gt;
==Active Records==&lt;br /&gt;
[http://guides.rubyonrails.org/active_record_basics.html Active Record] was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                                                                  	# is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                                                    	# find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')                             	# find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)&lt;br /&gt;
# find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                                                   	# find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')                 	# find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)               	# find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')                 	# create a fred&lt;br /&gt;
user_model.destroy(object)                                  	# destroy the user object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* Connection Pooling&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading eager loading]to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as [http://github.com/kabari/dm-couchdb-adapter/tree/master CouchDB], [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==NonSQL databases==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Comparison of ORM Features==&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==References ==&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.rubyforge.org Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_sk&amp;diff=86256</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 sk</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_sk&amp;diff=86256"/>
		<updated>2014-09-18T01:29:29Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: CSC/ECE 517 Fall 2014/ch1a 25 sk&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Object Relational Mapping==&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping] (ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Onject Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attribute attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent. &lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
&lt;br /&gt;
==Advantages ==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages ==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
 &lt;br /&gt;
==Features==&lt;br /&gt;
 &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
 &lt;br /&gt;
==Active Records==&lt;br /&gt;
[http://guides.rubyonrails.org/active_record_basics.html Active Record] was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                                                                  	# is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                                                    	# find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')                             	# find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)&lt;br /&gt;
# find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                                                   	# find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')                 	# find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)               	# find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')                 	# create a fred&lt;br /&gt;
user_model.destroy(object)                                  	# destroy the user object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* Connection Pooling&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading eager loading]to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as [http://github.com/kabari/dm-couchdb-adapter/tree/master CouchDB], [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==NonSQL databases==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Comparison of ORM Features==&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==References ==&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.rubyforge.org Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_sk&amp;diff=86248</id>
		<title>CSC/ECE 517 Fall 2014/ch1a 25 sk</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_sk&amp;diff=86248"/>
		<updated>2014-09-18T01:15:37Z</updated>

		<summary type="html">&lt;p&gt;Sdrangne: Created page with &amp;quot;==Introduction== [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping] (ORM, O/RM, and O/R mapping) in computer science is a programming technique fo...&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping] (ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Onject Relational Mapping is a programming technique in which a metadata descriptor is used to connect object code to a relational database. ORM converts data between type systems that are unable to coexist within relational databases and OOP languages.&lt;br /&gt;
 &lt;br /&gt;
In [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming], data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person object&amp;quot; with attribute attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.&lt;br /&gt;
 &lt;br /&gt;
The heart of the problem is translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent. &lt;br /&gt;
==Simple Explanation==&lt;br /&gt;
A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.&lt;br /&gt;
 &lt;br /&gt;
In other words, instead of something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
String sql = &amp;quot;SELECT ... FROM persons WHERE id = 10&amp;quot;&lt;br /&gt;
DbCommand cmd = new DbCommand(connection, sql);&lt;br /&gt;
Result res = cmd.Execute();&lt;br /&gt;
String name = res[0][&amp;quot;FIRST_NAME&amp;quot;];&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
you do something like this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = repository.GetPerson(10);&lt;br /&gt;
String name = p.FirstName;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Some also implement complex query systems, so you could do this:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Person p = Person.Get(Person.Properties.Id == 10);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The framework is what makes this code possible.&lt;br /&gt;
&lt;br /&gt;
==Advantages ==&lt;br /&gt;
In addition to the [http://en.wikipedia.org/wiki/Data_access data access] technique, ORM's benefits also include:&lt;br /&gt;
*First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to &amp;quot;get me all persons edited the last 24 hours&amp;quot; might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.&lt;br /&gt;
*Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the &amp;quot;plumbing&amp;quot; necessary to talk to the database.&lt;br /&gt;
*Simplified development because it automates object-to-table and table-to-object conversion, resulting in lower development and maintenance costs&lt;br /&gt;
*Less code compared to embedded SQL and handwritten stored procedures&lt;br /&gt;
*Transparent object caching in the application tier, improving system performance&lt;br /&gt;
*An optimized solution making an application faster and easier to maintain&lt;br /&gt;
&lt;br /&gt;
==Disadvantages ==&lt;br /&gt;
*ORM’s emergence in multiple application development has created disagreement among experts. Key concerns are that ORM does not perform well and that stored procedures might be a better solution.&lt;br /&gt;
*In addition, ORM dependence may result in poorly-designed databases in certain circumstances.&lt;br /&gt;
*Performance – like every &amp;quot;proxy&amp;quot; technology&lt;br /&gt;
*Complexity – learning curve&lt;br /&gt;
*Difficulty / inability to make complex queries&lt;br /&gt;
 &lt;br /&gt;
==Features==&lt;br /&gt;
 &lt;br /&gt;
Object-relational Mapping (ORM) frameworks unburden the designer of the complex translation between database and object space.&lt;br /&gt;
 &lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
 &lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table….&lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
 &lt;br /&gt;
ORM framework is used to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states. Most ORM tools rely heavily on metadata about both the database and objects, so that the objects need to know nothing about the database and the database doesn’t need to know anything about how the data is structured in the application. ORM provides a clean separation of concerns in a well-designed data application, and the database and application can each work with data in its native form. Database rows map to objects, thus making the program more easily accessible and allowing the usage of information in a way that is internally consistent and easy to understand. The ORM gives the programmer an ability to manipulate data with the programming language, instead of having to manipulate each attribute as its data type as obtained by the database management system.&lt;br /&gt;
 &lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
 &lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
 &lt;br /&gt;
==Active Records==&lt;br /&gt;
[http://guides.rubyonrails.org/active_record_basics.html Active Record] was described by Martin Fowler in his book Patterns of Enterprise Application Architecture.  Active Record is the M in [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]- the model - which is the layer of the system responsible for representing business data and logic. In Active Record, objects carry both persistent data and behavior which operates on that data. A database table or view is wrapped into a class and an object instance is tied to a single row in the table.  Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. In addition, Active Record allows you to validate the state of a model before it gets written into the database. &lt;br /&gt;
 &lt;br /&gt;
Active Record gives us several mechanisms, the most important being the ability to:&lt;br /&gt;
* Represent models and their data.&lt;br /&gt;
* Represent associations between these models.&lt;br /&gt;
* Represent inheritance hierarchies through related models.&lt;br /&gt;
* Validate models before they get persisted to the database.&lt;br /&gt;
* Perform database operations in an object-oriented fashion.&lt;br /&gt;
 &lt;br /&gt;
The naming conventions used in Active Records are :&lt;br /&gt;
* Database Table - Plural with underscores separating words (e.g., book_clubs).&lt;br /&gt;
* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).&lt;br /&gt;
 &lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
	create_table :users do |t|&lt;br /&gt;
  	t.string :name&lt;br /&gt;
  	t.string :email&lt;br /&gt;
  	t.string :age&lt;br /&gt;
            	  t.references :cheer&lt;br /&gt;
            	  t.references :post&lt;br /&gt;
 &lt;br /&gt;
  	t.timestamps 	# add creation and modification timestamps&lt;br /&gt;
	end&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def self.down    	# undo the table creation&lt;br /&gt;
	drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
The ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord. &lt;br /&gt;
 &lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
 &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user who's name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency. &lt;br /&gt;
 &lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
 &lt;br /&gt;
'''Pros''' -&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
* Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
* DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' -&lt;br /&gt;
* DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
==ORM Adaptor==&lt;br /&gt;
[https://github.com/ianwhite/orm_adapter ORM Adaptors] provide a single point of entry for popular ruby ORMs. Its target audience is gem authors who want to support more than one ORM.&lt;br /&gt;
ORM Adapter's goal is to support a minimum API used by most of the plugins that needs agnosticism beyond Active Model.&lt;br /&gt;
ORM Adapter will support only basic methods, as get, find_first, create! and so forth. It is not ORM Adapter's goal to support different query constructions, handle table joins, etc.&lt;br /&gt;
ORM adapter provides a consistent API for these basic class or 'factory' methods. It does not attempt to unify the behaviour of model instances returned by these methods. This means that unifying the behaviour of methods such as `model.save`, and `model.valid?` is beyond the scope of orm_adapter.&lt;br /&gt;
If you need complex queries, it is recommended to subclass ORM Adapters in your plugin and extend it expressing these query conditions as part of your domain logic.&lt;br /&gt;
Example :&lt;br /&gt;
require 'orm_adapter'&lt;br /&gt;
User                                                                                  	# is it an ActiveRecord, DM Resource, MongoMapper or MongoId Document?&lt;br /&gt;
User.to_adapter.find_first :name =&amp;gt; 'Fred'     	# we don't care!&lt;br /&gt;
user_model = User.to_adapter&lt;br /&gt;
user_model.get!(1)                                                    	# find a record by id&lt;br /&gt;
user_model.find_first(:name =&amp;gt; 'fred')                             	# find first fred&lt;br /&gt;
user_model.find_first(:level =&amp;gt; 'awesome', :id =&amp;gt; 23)&lt;br /&gt;
# find user 23, only if it's level is awesome&lt;br /&gt;
user_model.find_all                                                   	# find all users&lt;br /&gt;
user_model.find_all(:name =&amp;gt; 'fred')                 	# find all freds&lt;br /&gt;
user_model.find_all(:order =&amp;gt; :name)               	# find all freds, ordered by name&lt;br /&gt;
user_model.create!(:name =&amp;gt; 'fred')                 	# create a fred&lt;br /&gt;
user_model.destroy(object)                                  	# destroy the user object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Sequel==&lt;br /&gt;
&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] was originally developed by Sharon Rosner and the first release was in March 2007. It is based on the active record pattern. Sequel and Active Record share a lot of common features , for example association and inheritance. But Sequel handles these features in a much more flexible manner. Currently Sequel is at version 3.44.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
Some of the key features of sequel are,&lt;br /&gt;
* Connection Pooling&lt;br /&gt;
* Thread Safety&lt;br /&gt;
* [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading Eager Loading] / Lazy Loading&lt;br /&gt;
* Model Caching&lt;br /&gt;
* Supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==Data Mapper==&lt;br /&gt;
[http://datamapper.org/ DataMapper] is an Object Relational Mapper written in Ruby developed by Sam Smoot with the goal to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
A Data Mapper is a Data Access Layer that performs bidirectional transfer of data between a persistent data store (often a relational database) and an in memory data representation (the domain layer). The goal of the pattern is to keep the in memory representation and the persistent data store independent of each other and the data mapper itself. The layer is composed of one or more mappers (or Data Access Objects), performing the data transfer.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and some web services. With DataMapper, you define your mappings in your model. Your data store can develop independently of your model using Migrations.&lt;br /&gt;
 &lt;br /&gt;
Some features of Data Mapper are as follows :&lt;br /&gt;
* No need to write structural migrations&lt;br /&gt;
* Scoped relations&lt;br /&gt;
* Lazy loading on certain attribute types&lt;br /&gt;
* Strategic [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading eager loading]to avoid (N+1) queries&lt;br /&gt;
* Default support for composite and natural keys&lt;br /&gt;
* Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
* An API not too heavily oriented to SQL databases&lt;br /&gt;
 &lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as [http://github.com/kabari/dm-couchdb-adapter/tree/master CouchDB], [http://github.com/lritter/dm-solr-adapter/tree/master Apache Solr], and webservices such as [http://github.com/halorgium/dm-salesforce/tree/master Salesforce].&lt;br /&gt;
 &lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
 &lt;br /&gt;
  property :id,     	Serial	# key&lt;br /&gt;
  property :name,   	String, :required =&amp;gt; true, :unique =&amp;gt; true 	&lt;br /&gt;
  property :age,    	String, :required =&amp;gt; true, :length =&amp;gt; 3..20&lt;br /&gt;
  property :email,  	String&lt;br /&gt;
 &lt;br /&gt;
  has n, :posts      	# one to many association&lt;br /&gt;
  has n, :cheers      	# one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
==MyBatis/iBatis==&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Following is a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==Squeel==&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]unlocks the power of Arel in Rails applications with a handy block-based syntax. It is supporting in Rails 3 and 4. With Squeel, you can write subqueries, access named functions provided by RDMBS and more without writing SQL strings.&lt;br /&gt;
Squeel lets you write your Active Record queries with fewer strings, and more Ruby, by making the Arel awesomeness that lies beneath Active Record more accessible.&lt;br /&gt;
Squeel lets you rewrite...&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
...as...&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
 &lt;br /&gt;
Squeel enhances the normal Active Record query methods by enabling them to accept blocks. Inside a block, the Squeel query DSL can be used. Note the use of curly braces in the above example instead of parentheses. {} denotes a Squeel DSL query.&lt;br /&gt;
Stubs and keypaths are the two primary building blocks used in a Squeel DSL query.&lt;br /&gt;
Stubs are, for most intents and purposes, just like Symbols in a normal call to Relation#where (note the need for doubling up on the curly braces here, the first ones start the block, the second are the hash braces):&lt;br /&gt;
Person.where{{name =&amp;gt; ‘Ernie’ }}&lt;br /&gt;
You normally wouldn't bother using the DSL in this case, as a simple hash would suffice. However, stubs serve as a building block for keypaths, and keypaths are very handy.&lt;br /&gt;
A Squeel keypath is essentially a more concise and readable alternative to a deeply nested hash. For instance, in standard Active Record, you might join several associations like this to perform a query:&lt;br /&gt;
Person.joins(:articles =&amp;gt; { :comments =&amp;gt; :person}).references(:all)&lt;br /&gt;
With a keypath, this would look like:&lt;br /&gt;
Person.joins{articles.comments.person}.references(:all)&lt;br /&gt;
The Squeel DSL works its magic using instance_eval which means that inside a Squeel DSL block, self isn't the same thing that it is outside the block.&lt;br /&gt;
This carries with it an important implication: Instance variables and instance methods inside the block won't refer to your object's variables/methods.&lt;br /&gt;
Use one of the following methods to get access to the object's methods and variables:&lt;br /&gt;
* Assign the variable locally before the DSL block, and access it as you would normally.&lt;br /&gt;
* Supply an arity to the DSL block, as in Person.where{|q| q.name == @my_name} Downside: You'll need to prefix stubs, keypaths, and functions with the DSL object.&lt;br /&gt;
* Wrap the method or instance variable inside the block with my{}. Person.where{name == my{some_method_to_return_a_name}}&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
==Merb==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Merb Merb], short for &amp;quot;Mongrel+Erb&amp;quot;, is a model view controller framework written in Ruby. Merb was merged into Rails web framework on December 23, 2008 as part of the Ruby on Rails 3.0 release.&lt;br /&gt;
Merb itself provides only the controller of an MVC model which can be extended to create a full-stack application environment. This effectively means Merb itself is not an ORM but can accommodate other ORMs.&lt;br /&gt;
Some features of Merb are as follows :&lt;br /&gt;
* Speed - Merb is ORM, JavaScript library and template language agnostic, preferring plugins that add support for features rather than producing a monolithic library with everything in the core.&lt;br /&gt;
* Lightweight - Rather than trying to cram every feature into a single code, things are kept bare minimum without sacrificing anything important.&lt;br /&gt;
* Powerful and extensible - For any features not covered in Merb’s core, there are plugins.&lt;br /&gt;
Some basic Command distinction between Ruby on Rails and Merb :&lt;br /&gt;
{| class=&amp;quot;comparison&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
! Action&lt;br /&gt;
! Ruby on Rails&lt;br /&gt;
! Merb&lt;br /&gt;
|-&lt;br /&gt;
| Create new application 'app1' || rails new app1 || merb-gen app app1&lt;br /&gt;
|-&lt;br /&gt;
| Start server || rails server || merb&lt;br /&gt;
|-&lt;br /&gt;
| Start cluster of 3 beginning at port 3000 || N/A || merb -p 3000 -c 3&lt;br /&gt;
|-&lt;br /&gt;
| Interactive console || rails console || merb -i&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==NonSQL databases==&lt;br /&gt;
Instead of ORM we can also use Object-Oriented Database Management System (OODBMS) or document-oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form. Document oriented databases also eliminates the need to retrieve objects as data rows. Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path. Also OODBMS limits the extent of processing SQL queries. &lt;br /&gt;
A Relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not available while using XML files. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Comparison of ORM Features==&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==References ==&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented programming]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Data_access data access]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming]&lt;br /&gt;
# [http://guides.rubyonrails.org/active_record_basics.html Active Record]&lt;br /&gt;
# [http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture MVC]&lt;br /&gt;
# [http://sequel.rubyforge.org Sequel]&lt;br /&gt;
# [http://datamapper.org/ DataMapper] &lt;br /&gt;
# [http://wiki.rubyonrails.org/howtos/db-relationships/eager-loading Eager Loading]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;br /&gt;
# [http://www.techopedia.com/definition/24200/object-relational-mapping--orm ORM]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Merb Merb]&lt;br /&gt;
# [http://www.merbivore.com/ Merb Website]&lt;br /&gt;
# [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Spring_2013/ch1_1d_zk Object Relational Mapping Spring 2013]&lt;/div&gt;</summary>
		<author><name>Sdrangne</name></author>
	</entry>
</feed>