<?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=Knimgao</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=Knimgao"/>
	<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Special:Contributions/Knimgao"/>
	<updated>2026-09-13T11:03:12Z</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_E1465_oak&amp;diff=91065</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=91065"/>
		<updated>2014-10-30T01:06:40Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Comparison of Original and Refactored Code */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project 'Expertiza' by Refactoring the Users Controller.&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes and removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to the index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller's method as it indicates increased coupling. Coupling must be as less as possible and the view should have direct access to as few instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Before Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;After Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Similar approach for reduction of instance variables has been implemented in other methods like index, show_selection, etc.&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and further enhances the readability of the code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render :action =&amp;gt; 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(:user_id =&amp;gt; @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(action: AuthHelper::get_home_action(session[:user]), controller: AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render action: 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(user_id: @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Modified declarations of Arrays and Hashes&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = {&amp;quot;1&amp;quot; =&amp;gt; 25, &amp;quot;2&amp;quot; =&amp;gt; 50, &amp;quot;3&amp;quot; =&amp;gt; 100}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters =[]&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = Hash[&amp;quot;1&amp;quot; ,25 , &amp;quot;2&amp;quot;, 50, &amp;quot;3&amp;quot;, 100]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Removed unused methods like self.participants_in and commented out code.&lt;br /&gt;
&lt;br /&gt;
===Use of Routing Helpers===&lt;br /&gt;
Routing helpers are a simpler alternative to the otherwise complex hard coded URLs which reduce the readability of the code.Routing helpers allow us to declare possible common routes for a given controller. Routing helpers have been implemented since they maintain consistency even if changes are made to the routing paths. &lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        get_role&lt;br /&gt;
        if @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
          render :action =&amp;gt; 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
        redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        role=get_role&lt;br /&gt;
        if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
          render action: 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to users_path  #Replaced URL with routing helper &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
      redirect_to users_path  #Replaced URL with routing helper&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Replace find_by_.. with where in querying===&lt;br /&gt;
Rails 4 conventions dictate the use of 'where()' over the use of 'find_by_...' methods while querying ActiveRecords. The code has been refactored to replace the usages of find_by.. with where().&lt;br /&gt;
&lt;br /&gt;
Before Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Comparison of Original and Refactored Code==&lt;br /&gt;
&lt;br /&gt;
Major refactoring revolved around moving lines of codes between methods, modifying array and hash declarations, using helper methods for avoiding multiple instance variables in controller methods and implementing Ruby Conventions.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Lines of Code&lt;br /&gt;
&lt;br /&gt;
Original : 248&amp;lt;br&amp;gt;&lt;br /&gt;
Post Refactoring : 224&lt;br /&gt;
&lt;br /&gt;
*Code Complexity (Compared on Code Climate)&lt;br /&gt;
&lt;br /&gt;
Original UsersController&amp;lt;ref name=&amp;quot;originaluserscontroller&amp;gt;''Original UsersController'' https://codeclimate.com/github/expertiza/expertiza/UsersController&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
Refactored UsersController&amp;lt;ref name=&amp;quot;refactoreduserscontroller&amp;gt;''Refactored UsersController'' https://codeclimate.com/repos/5450f2eae30ba012a6011c01/UsersController&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Further Readings==&lt;br /&gt;
1.[https://github.com/ameyp1992/expertiza.git Git Repository]&lt;br /&gt;
&lt;br /&gt;
2.[http://wiki.expertiza.ncsu.edu/index.php/Development:Setup:Linux:Debian Expertiza Setup]&lt;br /&gt;
&lt;br /&gt;
3.[https://docs.google.com/document/d/1FZCL9KWSdVNsX9BowuZ3gxbCOJoiWX-GVLctSZei3No/edit?pli=1#heading=h.2y12n9sli9rd Project requirements]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=91055</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=91055"/>
		<updated>2014-10-30T01:02:10Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project 'Expertiza' by Refactoring the Users Controller.&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes and removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to the index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller's method as it indicates increased coupling. Coupling must be as less as possible and the view should have direct access to as few instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Before Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;After Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Similar approach for reduction of instance variables has been implemented in other methods like index, show_selection, etc.&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and further enhances the readability of the code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render :action =&amp;gt; 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(:user_id =&amp;gt; @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(action: AuthHelper::get_home_action(session[:user]), controller: AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render action: 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(user_id: @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Modified declarations of Arrays and Hashes&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = {&amp;quot;1&amp;quot; =&amp;gt; 25, &amp;quot;2&amp;quot; =&amp;gt; 50, &amp;quot;3&amp;quot; =&amp;gt; 100}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters =[]&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = Hash[&amp;quot;1&amp;quot; ,25 , &amp;quot;2&amp;quot;, 50, &amp;quot;3&amp;quot;, 100]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Removed unused methods like self.participants_in and commented out code.&lt;br /&gt;
&lt;br /&gt;
===Use of Routing Helpers===&lt;br /&gt;
Routing helpers are a simpler alternative to the otherwise complex hard coded URLs which reduce the readability of the code.Routing helpers allow us to declare possible common routes for a given controller. Routing helpers have been implemented since they maintain consistency even if changes are made to the routing paths. &lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        get_role&lt;br /&gt;
        if @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
          render :action =&amp;gt; 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
        redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        role=get_role&lt;br /&gt;
        if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
          render action: 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to users_path  #Replaced URL with routing helper &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
      redirect_to users_path  #Replaced URL with routing helper&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Replace find_by_.. with where in querying===&lt;br /&gt;
Rails 4 conventions dictate the use of 'where()' over the use of 'find_by_...' methods while querying ActiveRecords. The code has been refactored to replace the usages of find_by.. with where().&lt;br /&gt;
&lt;br /&gt;
Before Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Comparison of Original and Refactored Code==&lt;br /&gt;
&lt;br /&gt;
Major refactoring revolved around moving lines of codes between methods, modifying array and hash declarations, using helper methods for avoiding multiple instance variables and implementing Ruby Conventions.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Lines of Code&lt;br /&gt;
&lt;br /&gt;
Original : 248&amp;lt;br&amp;gt;&lt;br /&gt;
Post Refactoring : 224&lt;br /&gt;
&lt;br /&gt;
*Code Complexity (Compared on Code Climate)&lt;br /&gt;
&lt;br /&gt;
Original UsersController&amp;lt;ref name=&amp;quot;originaluserscontroller&amp;gt;''Original UsersController'' https://codeclimate.com/github/expertiza/expertiza/UsersController&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
Refactored UsersController&amp;lt;ref name=&amp;quot;refactoreduserscontroller&amp;gt;''Refactored UsersController'' https://codeclimate.com/repos/5450f2eae30ba012a6011c01/UsersController&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Further Readings==&lt;br /&gt;
1.[https://github.com/ameyp1992/expertiza.git Git Repository]&lt;br /&gt;
&lt;br /&gt;
2.[http://wiki.expertiza.ncsu.edu/index.php/Development:Setup:Linux:Debian Expertiza Setup]&lt;br /&gt;
&lt;br /&gt;
3.[https://docs.google.com/document/d/1FZCL9KWSdVNsX9BowuZ3gxbCOJoiWX-GVLctSZei3No/edit?pli=1#heading=h.2y12n9sli9rd Project requirements]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=91050</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=91050"/>
		<updated>2014-10-30T00:53:02Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Project Description */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project 'Expertiza' by Refactoring the Users Controller.&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes and removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to the index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller's method as it indicates increased coupling. Coupling must be as less as possible and the view should have direct access to as few instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Before Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;After Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Similar approach for reduction of instance variables has been implemented in other methods like index, show_selection, etc.&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and further enhances the readability of the code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render :action =&amp;gt; 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(:user_id =&amp;gt; @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(action: AuthHelper::get_home_action(session[:user]), controller: AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render action: 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(user_id: @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Modified declarations of Arrays and Hashes&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = {&amp;quot;1&amp;quot; =&amp;gt; 25, &amp;quot;2&amp;quot; =&amp;gt; 50, &amp;quot;3&amp;quot; =&amp;gt; 100}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters =[]&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = Hash[&amp;quot;1&amp;quot; ,25 , &amp;quot;2&amp;quot;, 50, &amp;quot;3&amp;quot;, 100]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Removed unused methods like self.participants_in and commented out code.&lt;br /&gt;
&lt;br /&gt;
===Use of Routing Helpers===&lt;br /&gt;
Routing helpers are a simpler alternative to the otherwise complex hard coded URLs which reduce the readability of the code.Routing helpers allow us to declare possible common routes for a given controller. Routing helpers have been implemented since they maintain consistency even if changes are made to the routing paths. &lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        get_role&lt;br /&gt;
        if @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
          render :action =&amp;gt; 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
        redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        role=get_role&lt;br /&gt;
        if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
          render action: 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to users_path  #Replaced URL with routing helper &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
      redirect_to users_path  #Replaced URL with routing helper&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Replace find_by_.. with where in querying===&lt;br /&gt;
Rails 4 conventions dictate the use of 'where()' over the use of 'find_by_...' methods while querying ActiveRecords. The code has been refactored to replace the usages of find_by.. with where().&lt;br /&gt;
&lt;br /&gt;
Before Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Further Readings==&lt;br /&gt;
1.[https://github.com/ameyp1992/expertiza.git Git Repository]&lt;br /&gt;
&lt;br /&gt;
2.[http://wiki.expertiza.ncsu.edu/index.php/Development:Setup:Linux:Debian Expertiza Setup]&lt;br /&gt;
&lt;br /&gt;
3.[https://docs.google.com/document/d/1FZCL9KWSdVNsX9BowuZ3gxbCOJoiWX-GVLctSZei3No/edit?pli=1#heading=h.2y12n9sli9rd Project requirements]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90429</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90429"/>
		<updated>2014-10-29T04:57:10Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project 'Expertiza' by Refactoring the Users Controller.&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes and removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Original lines of code : 243&lt;br /&gt;
&lt;br /&gt;
Lines after refactoring: 225&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to the index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller's method as it indicates increased coupling. Coupling must be as less as possible and the view should have direct access to as few instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Before Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;After Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Similar approach for reduction of instance variables has been implemented in other methods like index, show_selection, etc.&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and further enhances the readability of the code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render :action =&amp;gt; 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(:user_id =&amp;gt; @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(action: AuthHelper::get_home_action(session[:user]), controller: AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render action: 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(user_id: @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Modified declarations of Arrays and Hashes&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = {&amp;quot;1&amp;quot; =&amp;gt; 25, &amp;quot;2&amp;quot; =&amp;gt; 50, &amp;quot;3&amp;quot; =&amp;gt; 100}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters =[]&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = Hash[&amp;quot;1&amp;quot; ,25 , &amp;quot;2&amp;quot;, 50, &amp;quot;3&amp;quot;, 100]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Removed unused methods like self.participants_in and commented out code.&lt;br /&gt;
&lt;br /&gt;
===Use of Routing Helpers===&lt;br /&gt;
Routing helpers are a simpler alternative to the otherwise complex hard coded URLs which reduce the readability of the code.Routing helpers allow us to declare possible common routes for a given controller. Routing helpers have been implemented since they maintain consistency even if changes are made to the routing paths. &lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        get_role&lt;br /&gt;
        if @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
          render :action =&amp;gt; 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
        redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        role=get_role&lt;br /&gt;
        if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
          render action: 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to users_path  #Replaced URL with routing helper &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
      redirect_to users_path  #Replaced URL with routing helper&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Replace find_by_.. with where in querying===&lt;br /&gt;
Rails 4 conventions dictate the use of 'where()' over the use of 'find_by_...' methods while querying ActiveRecords. The code has been refactored to replace the usages of find_by.. with where().&lt;br /&gt;
&lt;br /&gt;
Before Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Further Readings==&lt;br /&gt;
1.[https://github.com/ameyp1992/expertiza.git Git Repository]&lt;br /&gt;
&lt;br /&gt;
2.[http://wiki.expertiza.ncsu.edu/index.php/Development:Setup:Linux:Debian Expertiza Setup]&lt;br /&gt;
&lt;br /&gt;
3.[https://docs.google.com/document/d/1FZCL9KWSdVNsX9BowuZ3gxbCOJoiWX-GVLctSZei3No/edit?pli=1#heading=h.2y12n9sli9rd Project requirements]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90428</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90428"/>
		<updated>2014-10-29T04:56:41Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project 'Expertiza' by Refactoring the Users Controller.&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes and removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Original lines of code : 243&lt;br /&gt;
&lt;br /&gt;
Lines after refactoring: 225&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to the index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller's method as it indicates increased coupling. Coupling must be as less as possible and the view should have direct access to as few instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Before Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;After Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Similar approach for reduction of instance variables has been implemented in other methods like index, show_selection, etc.&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and further enhances the readability of the code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render :action =&amp;gt; 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(:user_id =&amp;gt; @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(action: AuthHelper::get_home_action(session[:user]), controller: AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render action: 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(user_id: @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Modified declarations of Arrays and Hashes&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = {&amp;quot;1&amp;quot; =&amp;gt; 25, &amp;quot;2&amp;quot; =&amp;gt; 50, &amp;quot;3&amp;quot; =&amp;gt; 100}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters =[]&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = Hash[&amp;quot;1&amp;quot; ,25 , &amp;quot;2&amp;quot;, 50, &amp;quot;3&amp;quot;, 100]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Removed unused methods like self.participants_in and commented out code.&lt;br /&gt;
&lt;br /&gt;
===Use of Routing Helpers===&lt;br /&gt;
Routing helpers are a simpler alternative to the otherwise complex hard coded URLs which reduce the readability of the code.Routing helpers allow us to declare possible common routes for a given controller. Routing helpers have been implemented since they maintain consistency even if changes are made to the routing paths. &lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        get_role&lt;br /&gt;
        if @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
          render :action =&amp;gt; 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
        redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        role=get_role&lt;br /&gt;
        if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
          render action: 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to users_path  #Replaced URL with routing helper &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
      redirect_to users_path  #Replaced URL with routing helper&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Replace find_by_.. with where in querying===&lt;br /&gt;
Rails 4 conventions dictate the use of 'where()' over the use of 'find_by_...' methods while querying ActiveRecords. The code has been refactored to replace the usages of find_by.. with where().&lt;br /&gt;
&lt;br /&gt;
Before Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90426</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90426"/>
		<updated>2014-10-29T04:55:27Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project 'Expertiza' by Refactoring the Users Controller.&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes and removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Original lines of code : 243&lt;br /&gt;
&lt;br /&gt;
Lines after refactoring: 225&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to the index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller's method as it indicates increased coupling. Coupling must be as less as possible and the view should have direct access to as few instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Before Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;After Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Similar approach for reduction of instance variables has been implemented in other methods like index, show_selection, etc.&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and further enhances the readability of the code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render :action =&amp;gt; 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(:user_id =&amp;gt; @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(action: AuthHelper::get_home_action(session[:user]), controller: AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render action: 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(user_id: @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Modified declarations of Arrays and Hashes&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = {&amp;quot;1&amp;quot; =&amp;gt; 25, &amp;quot;2&amp;quot; =&amp;gt; 50, &amp;quot;3&amp;quot; =&amp;gt; 100}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters =[]&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = Hash[&amp;quot;1&amp;quot; ,25 , &amp;quot;2&amp;quot;, 50, &amp;quot;3&amp;quot;, 100]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Removed unused methods like self.participants_in and commented out code.&lt;br /&gt;
&lt;br /&gt;
===Use of Routing Helpers===&lt;br /&gt;
Routing helpers are a simpler alternative to the otherwise complex hard coded URLs which reduce the readability of the code.Routing helpers allow us to declare possible common routes for a given controller. Routing helpers have been implemented since they maintain consistency even if changes are made to the routing paths. &lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        get_role&lt;br /&gt;
        if @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
          render :action =&amp;gt; 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
        redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        role=get_role&lt;br /&gt;
        if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
          render action: 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to users_path  #Replaced URL with routing helper &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
      redirect_to users_path  #Replaced URL with routing helper&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Replace find_by_.. with where in querying===&lt;br /&gt;
Rails 4 conventions dictate the use of 'where()' over the use of 'find_by_...' methods while querying ActiveRecords. The code has been refactored to replace the usages of find_by.. with where().&lt;br /&gt;
&lt;br /&gt;
Before Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
1.[https://github.com/ameyp1992/expertiza.git Git Repository]&lt;br /&gt;
&lt;br /&gt;
2.[http://wiki.expertiza.ncsu.edu/index.php/Development:Setup:Linux:Debian Expertiza Setup]&lt;br /&gt;
&lt;br /&gt;
3.[https://docs.google.com/document/d/1FZCL9KWSdVNsX9BowuZ3gxbCOJoiWX-GVLctSZei3No/edit?pli=1#heading=h.2y12n9sli9rd Project requirements]&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90425</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90425"/>
		<updated>2014-10-29T04:54:44Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project 'Expertiza' by Refactoring the Users Controller.&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes and removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Original lines of code : 243&lt;br /&gt;
&lt;br /&gt;
Lines after refactoring: 225&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to the index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller's method as it indicates increased coupling. Coupling must be as less as possible and the view should have direct access to as few instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Before Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;After Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Similar approach for reduction of instance variables has been implemented in other methods like index, show_selection, etc.&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and further enhances the readability of the code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render :action =&amp;gt; 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(:user_id =&amp;gt; @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(action: AuthHelper::get_home_action(session[:user]), controller: AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render action: 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(user_id: @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Modified declarations of Arrays and Hashes&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = {&amp;quot;1&amp;quot; =&amp;gt; 25, &amp;quot;2&amp;quot; =&amp;gt; 50, &amp;quot;3&amp;quot; =&amp;gt; 100}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters =[]&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = Hash[&amp;quot;1&amp;quot; ,25 , &amp;quot;2&amp;quot;, 50, &amp;quot;3&amp;quot;, 100]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Removed unused methods like self.participants_in and commented out code.&lt;br /&gt;
&lt;br /&gt;
===Use of Routing Helpers===&lt;br /&gt;
Routing helpers are a simpler alternative to the otherwise complex hard coded URLs which reduce the readability of the code.Routing helpers allow us to declare possible common routes for a given controller. Routing helpers have been implemented since they maintain consistency even if changes are made to the routing paths. &lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        get_role&lt;br /&gt;
        if @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
          render :action =&amp;gt; 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
        redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        role=get_role&lt;br /&gt;
        if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
          render action: 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to users_path  #Replaced URL with routing helper &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
      redirect_to users_path  #Replaced URL with routing helper&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Replace find_by_.. with where in querying===&lt;br /&gt;
Rails 4 conventions dictate the use of 'where()' over the use of 'find_by_...' methods while querying ActiveRecords. The code has been refactored to replace the usages of find_by.. with where().&lt;br /&gt;
&lt;br /&gt;
Before Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
#[https://github.com/ameyp1992/expertiza.git Git Repository]&lt;br /&gt;
&lt;br /&gt;
#[http://wiki.expertiza.ncsu.edu/index.php/Development:Setup:Linux:Debian Expertiza Setup]&lt;br /&gt;
&lt;br /&gt;
#[https://docs.google.com/document/d/1FZCL9KWSdVNsX9BowuZ3gxbCOJoiWX-GVLctSZei3No/edit?pli=1#heading=h.2y12n9sli9rd Project requirements]&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90424</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90424"/>
		<updated>2014-10-29T04:53:07Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project 'Expertiza' by Refactoring the Users Controller.&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes and removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Original lines of code : 243&lt;br /&gt;
&lt;br /&gt;
Lines after refactoring: 225&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to the index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller's method as it indicates increased coupling. Coupling must be as less as possible and the view should have direct access to as few instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Before Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;After Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Similar approach for reduction of instance variables has been implemented in other methods like index, show_selection, etc.&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and further enhances the readability of the code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render :action =&amp;gt; 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(:user_id =&amp;gt; @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(action: AuthHelper::get_home_action(session[:user]), controller: AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render action: 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(user_id: @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Modified declarations of Arrays and Hashes&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = {&amp;quot;1&amp;quot; =&amp;gt; 25, &amp;quot;2&amp;quot; =&amp;gt; 50, &amp;quot;3&amp;quot; =&amp;gt; 100}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters =[]&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = Hash[&amp;quot;1&amp;quot; ,25 , &amp;quot;2&amp;quot;, 50, &amp;quot;3&amp;quot;, 100]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Removed unused methods like self.participants_in and commented out code.&lt;br /&gt;
&lt;br /&gt;
===Use of Routing Helpers===&lt;br /&gt;
Routing helpers are a simpler alternative to the otherwise complex hard coded URLs which reduce the readability of the code.Routing helpers allow us to declare possible common routes for a given controller. Routing helpers have been implemented since they maintain consistency even if changes are made to the routing paths. &lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        get_role&lt;br /&gt;
        if @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
          render :action =&amp;gt; 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
        redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        role=get_role&lt;br /&gt;
        if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
          render action: 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to users_path  #Replaced URL with routing helper &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
      redirect_to users_path  #Replaced URL with routing helper&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Replace find_by_.. with where in querying===&lt;br /&gt;
Rails 4 conventions dictate the use of 'where()' over the use of 'find_by_...' methods while querying ActiveRecords. The code has been refactored to replace the usages of find_by.. with where().&lt;br /&gt;
&lt;br /&gt;
Before Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*[https://github.com/ameyp1992/expertiza.git Git Repository]&lt;br /&gt;
&lt;br /&gt;
*[http://wiki.expertiza.ncsu.edu/index.php/Development:Setup:Linux:Debian Expertiza Setup]&lt;br /&gt;
&lt;br /&gt;
*[https://docs.google.com/document/d/1FZCL9KWSdVNsX9BowuZ3gxbCOJoiWX-GVLctSZei3No/edit?pli=1#heading=h.2y12n9sli9rd Project requirements]&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90423</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90423"/>
		<updated>2014-10-29T04:46:05Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Code Cleanup */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project 'Expertiza' by Refactoring the Users Controller.&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes and removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Original lines of code : 243&lt;br /&gt;
&lt;br /&gt;
Lines after refactoring: 225&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to the index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller's method as it indicates increased coupling. Coupling must be as less as possible and the view should have direct access to as few instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Before Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;After Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Similar approach for reduction of instance variables has been implemented in other methods like index, show_selection, etc.&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and further enhances the readability of the code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render :action =&amp;gt; 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(:user_id =&amp;gt; @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(action: AuthHelper::get_home_action(session[:user]), controller: AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render action: 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(user_id: @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Modified declarations of Arrays and Hashes&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = {&amp;quot;1&amp;quot; =&amp;gt; 25, &amp;quot;2&amp;quot; =&amp;gt; 50, &amp;quot;3&amp;quot; =&amp;gt; 100}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters =[]&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = Hash[&amp;quot;1&amp;quot; ,25 , &amp;quot;2&amp;quot;, 50, &amp;quot;3&amp;quot;, 100]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Removed unused methods like self.participants_in and commented out code.&lt;br /&gt;
&lt;br /&gt;
===Use of Routing Helpers===&lt;br /&gt;
Routing helpers are a simpler alternative to the otherwise complex hard coded URLs which reduce the readability of the code.Routing helpers allow us to declare possible common routes for a given controller. Routing helpers have been implemented since they maintain consistency even if changes are made to the routing paths. &lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        get_role&lt;br /&gt;
        if @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
          render :action =&amp;gt; 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
        redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        role=get_role&lt;br /&gt;
        if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
          render action: 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to users_path  #Replaced URL with routing helper &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
      redirect_to users_path  #Replaced URL with routing helper&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Replace find_by_.. with where in querying===&lt;br /&gt;
Rails 4 conventions dictate the use of 'where()' over the use of 'find_by_...' methods while querying ActiveRecords. The code has been refactored to replace the usages of find_by.. with where().&lt;br /&gt;
&lt;br /&gt;
Before Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
[https://github.com/ameyp1992/expertiza.git Git Repository]&lt;br /&gt;
&lt;br /&gt;
[http://wiki.expertiza.ncsu.edu/index.php/Development:Setup:Linux:Debian Expertiza Setup]&lt;br /&gt;
&lt;br /&gt;
[https://docs.google.com/document/d/1FZCL9KWSdVNsX9BowuZ3gxbCOJoiWX-GVLctSZei3No/edit?pli=1#heading=h.2y12n9sli9rd Project requirements]&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90422</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90422"/>
		<updated>2014-10-29T04:44:37Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Instance Variable Reductions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project 'Expertiza' by Refactoring the Users Controller.&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes and removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Original lines of code : 243&lt;br /&gt;
&lt;br /&gt;
Lines after refactoring: 225&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to the index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller's method as it indicates increased coupling. Coupling must be as less as possible and the view should have direct access to as few instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Before Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;After Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Similar approach for reduction of instance variables has been implemented in other methods like index, show_selection, etc.&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and enhanced readability of code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render :action =&amp;gt; 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(:user_id =&amp;gt; @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(action: AuthHelper::get_home_action(session[:user]), controller: AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render action: 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(user_id: @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Modified declarations of Arrays and Hashes&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = {&amp;quot;1&amp;quot; =&amp;gt; 25, &amp;quot;2&amp;quot; =&amp;gt; 50, &amp;quot;3&amp;quot; =&amp;gt; 100}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters =[]&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = Hash[&amp;quot;1&amp;quot; ,25 , &amp;quot;2&amp;quot;, 50, &amp;quot;3&amp;quot;, 100]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Removed unused methods like self.participants_in and commented out code.&lt;br /&gt;
&lt;br /&gt;
===Use of Routing Helpers===&lt;br /&gt;
Routing helpers are a simpler alternative to the otherwise complex hard coded URLs which reduce the readability of the code.Routing helpers allow us to declare possible common routes for a given controller. Routing helpers have been implemented since they maintain consistency even if changes are made to the routing paths. &lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        get_role&lt;br /&gt;
        if @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
          render :action =&amp;gt; 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
        redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        role=get_role&lt;br /&gt;
        if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
          render action: 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to users_path  #Replaced URL with routing helper &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
      redirect_to users_path  #Replaced URL with routing helper&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Replace find_by_.. with where in querying===&lt;br /&gt;
Rails 4 conventions dictate the use of 'where()' over the use of 'find_by_...' methods while querying ActiveRecords. The code has been refactored to replace the usages of find_by.. with where().&lt;br /&gt;
&lt;br /&gt;
Before Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
[https://github.com/ameyp1992/expertiza.git Git Repository]&lt;br /&gt;
&lt;br /&gt;
[http://wiki.expertiza.ncsu.edu/index.php/Development:Setup:Linux:Debian Expertiza Setup]&lt;br /&gt;
&lt;br /&gt;
[https://docs.google.com/document/d/1FZCL9KWSdVNsX9BowuZ3gxbCOJoiWX-GVLctSZei3No/edit?pli=1#heading=h.2y12n9sli9rd Project requirements]&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90421</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90421"/>
		<updated>2014-10-29T04:39:11Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* RESTful style implementation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project 'Expertiza' by Refactoring the Users Controller.&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes and removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Original lines of code : 243&lt;br /&gt;
&lt;br /&gt;
Lines after refactoring: 225&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to the index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller action as it indicates towards increased coupling. We want to reduce the coupling as much as possible and view should have direct access to as few instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Before Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;After Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and enhanced readability of code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render :action =&amp;gt; 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(:user_id =&amp;gt; @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(action: AuthHelper::get_home_action(session[:user]), controller: AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render action: 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(user_id: @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Modified declarations of Arrays and Hashes&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = {&amp;quot;1&amp;quot; =&amp;gt; 25, &amp;quot;2&amp;quot; =&amp;gt; 50, &amp;quot;3&amp;quot; =&amp;gt; 100}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters =[]&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = Hash[&amp;quot;1&amp;quot; ,25 , &amp;quot;2&amp;quot;, 50, &amp;quot;3&amp;quot;, 100]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Removed unused methods like self.participants_in and commented out code.&lt;br /&gt;
&lt;br /&gt;
===Use of Routing Helpers===&lt;br /&gt;
Routing helpers are a simpler alternative to the otherwise complex hard coded URLs which reduce the readability of the code.Routing helpers allow us to declare possible common routes for a given controller. Routing helpers have been implemented since they maintain consistency even if changes are made to the routing paths. &lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        get_role&lt;br /&gt;
        if @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
          render :action =&amp;gt; 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
        redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        role=get_role&lt;br /&gt;
        if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
          render action: 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to users_path  #Replaced URL with routing helper &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
      redirect_to users_path  #Replaced URL with routing helper&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Replace find_by_.. with where in querying===&lt;br /&gt;
Rails 4 conventions dictate the use of 'where()' over the use of 'find_by_...' methods while querying ActiveRecords. The code has been refactored to replace the usages of find_by.. with where().&lt;br /&gt;
&lt;br /&gt;
Before Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
[https://github.com/ameyp1992/expertiza.git Git Repository]&lt;br /&gt;
&lt;br /&gt;
[http://wiki.expertiza.ncsu.edu/index.php/Development:Setup:Linux:Debian Expertiza Setup]&lt;br /&gt;
&lt;br /&gt;
[https://docs.google.com/document/d/1FZCL9KWSdVNsX9BowuZ3gxbCOJoiWX-GVLctSZei3No/edit?pli=1#heading=h.2y12n9sli9rd Project requirements]&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90420</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90420"/>
		<updated>2014-10-29T04:37:45Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Project Description */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project 'Expertiza' by Refactoring the Users Controller.&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes and removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Original lines of code : 243&lt;br /&gt;
&lt;br /&gt;
Lines after refactoring: 225&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller action as it indicates towards increased coupling. We want to reduce the coupling as much as possible and view should have direct access to as few instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Before Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;After Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and enhanced readability of code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render :action =&amp;gt; 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(:user_id =&amp;gt; @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(action: AuthHelper::get_home_action(session[:user]), controller: AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render action: 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(user_id: @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Modified declarations of Arrays and Hashes&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = {&amp;quot;1&amp;quot; =&amp;gt; 25, &amp;quot;2&amp;quot; =&amp;gt; 50, &amp;quot;3&amp;quot; =&amp;gt; 100}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters =[]&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = Hash[&amp;quot;1&amp;quot; ,25 , &amp;quot;2&amp;quot;, 50, &amp;quot;3&amp;quot;, 100]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Removed unused methods like self.participants_in and commented out code.&lt;br /&gt;
&lt;br /&gt;
===Use of Routing Helpers===&lt;br /&gt;
Routing helpers are a simpler alternative to the otherwise complex hard coded URLs which reduce the readability of the code.Routing helpers allow us to declare possible common routes for a given controller. Routing helpers have been implemented since they maintain consistency even if changes are made to the routing paths. &lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        get_role&lt;br /&gt;
        if @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
          render :action =&amp;gt; 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
        redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        role=get_role&lt;br /&gt;
        if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
          render action: 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to users_path  #Replaced URL with routing helper &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
      redirect_to users_path  #Replaced URL with routing helper&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Replace find_by_.. with where in querying===&lt;br /&gt;
Rails 4 conventions dictate the use of 'where()' over the use of 'find_by_...' methods while querying ActiveRecords. The code has been refactored to replace the usages of find_by.. with where().&lt;br /&gt;
&lt;br /&gt;
Before Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
[https://github.com/ameyp1992/expertiza.git Git Repository]&lt;br /&gt;
&lt;br /&gt;
[http://wiki.expertiza.ncsu.edu/index.php/Development:Setup:Linux:Debian Expertiza Setup]&lt;br /&gt;
&lt;br /&gt;
[https://docs.google.com/document/d/1FZCL9KWSdVNsX9BowuZ3gxbCOJoiWX-GVLctSZei3No/edit?pli=1#heading=h.2y12n9sli9rd Project requirements]&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90419</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90419"/>
		<updated>2014-10-29T04:36:18Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project 'Expertiza' by Refactoring the Users Controller.&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes,removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Original lines of code : 243&lt;br /&gt;
&lt;br /&gt;
Lines after refactoring: 225&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller action as it indicates towards increased coupling. We want to reduce the coupling as much as possible and view should have direct access to as few instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Before Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;After Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and enhanced readability of code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render :action =&amp;gt; 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(:user_id =&amp;gt; @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(action: AuthHelper::get_home_action(session[:user]), controller: AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render action: 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(user_id: @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Modified declarations of Arrays and Hashes&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = {&amp;quot;1&amp;quot; =&amp;gt; 25, &amp;quot;2&amp;quot; =&amp;gt; 50, &amp;quot;3&amp;quot; =&amp;gt; 100}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters =[]&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = Hash[&amp;quot;1&amp;quot; ,25 , &amp;quot;2&amp;quot;, 50, &amp;quot;3&amp;quot;, 100]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Removed unused methods like self.participants_in and commented out code.&lt;br /&gt;
&lt;br /&gt;
===Use of Routing Helpers===&lt;br /&gt;
Routing helpers are a simpler alternative to the otherwise complex hard coded URLs which reduce the readability of the code.Routing helpers allow us to declare possible common routes for a given controller. Routing helpers have been implemented since they maintain consistency even if changes are made to the routing paths. &lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        get_role&lt;br /&gt;
        if @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
          render :action =&amp;gt; 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
        redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        role=get_role&lt;br /&gt;
        if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
          render action: 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to users_path  #Replaced URL with routing helper &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
      redirect_to users_path  #Replaced URL with routing helper&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Replace find_by_.. with where in querying===&lt;br /&gt;
Rails 4 conventions dictate the use of 'where()' over the use of 'find_by_...' methods while querying ActiveRecords. The code has been refactored to replace the usages of find_by.. with where().&lt;br /&gt;
&lt;br /&gt;
Before Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
[https://github.com/ameyp1992/expertiza.git Git Repository]&lt;br /&gt;
&lt;br /&gt;
[http://wiki.expertiza.ncsu.edu/index.php/Development:Setup:Linux:Debian Expertiza Setup]&lt;br /&gt;
&lt;br /&gt;
[https://docs.google.com/document/d/1FZCL9KWSdVNsX9BowuZ3gxbCOJoiWX-GVLctSZei3No/edit?pli=1#heading=h.2y12n9sli9rd Project requirements]&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90418</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=90418"/>
		<updated>2014-10-29T04:32:38Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project Expertiza with main focus of Refactoring the Users Controller.&lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes,removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Original lines of code : 243&lt;br /&gt;
&lt;br /&gt;
Lines after refactoring: 225&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller action as it indicates towards increased coupling. We want to reduce the coupling as much as possible and view should have direct access to as few instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Before Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;After Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and enhanced readability of code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render :action =&amp;gt; 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(:user_id =&amp;gt; @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(action: AuthHelper::get_home_action(session[:user]), controller: AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render action: 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(user_id: @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Modified declarations of Arrays and Hashes&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = {&amp;quot;1&amp;quot; =&amp;gt; 25, &amp;quot;2&amp;quot; =&amp;gt; 50, &amp;quot;3&amp;quot; =&amp;gt; 100}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 @letters =[]&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 paginate_options = Hash[&amp;quot;1&amp;quot; ,25 , &amp;quot;2&amp;quot;, 50, &amp;quot;3&amp;quot;, 100]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Removed unused methods like self.participants_in and commented out code.&lt;br /&gt;
&lt;br /&gt;
===Use of Routing Helpers===&lt;br /&gt;
Routing helpers are a simpler alternative to the otherwise complex hard coded URLs which reduce the readability of the code.Routing helpers allow us to declare possible common routes for a given controller. Routing helpers have been implemented since they maintain consistency even if changes are made to the routing paths. &lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        get_role&lt;br /&gt;
        if @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
          render :action =&amp;gt; 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
        redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        role=get_role&lt;br /&gt;
        if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
          render action: 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to users_path  #Replaced URL with routing helper &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
      redirect_to users_path  #Replaced URL with routing helper&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Replace find_by_.. with where in querying===&lt;br /&gt;
Rails 4 conventions dictate the use of 'where()' over the use of 'find_by_...' methods while querying ActiveRecords. The code has been refactored to replace the usages of find_by.. with where().&lt;br /&gt;
&lt;br /&gt;
Before Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
[https://github.com/ameyp1992/expertiza.git Git Repository]&lt;br /&gt;
&lt;br /&gt;
[http://wiki.expertiza.ncsu.edu/index.php/Development:Setup:Linux:Debian Expertiza Setup]&lt;br /&gt;
&lt;br /&gt;
[https://docs.google.com/document/d/1FZCL9KWSdVNsX9BowuZ3gxbCOJoiWX-GVLctSZei3No/edit?pli=1#heading=h.2y12n9sli9rd Project requirements]&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89631</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89631"/>
		<updated>2014-10-25T04:49:09Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Replace find_by_.. by where in querying */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects, and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project Expertiza with main focus of Refactoring the Users Controller. &lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes,removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller action as it indicates towards increased coupling. We want to reduce the coupling as much as possible and view should have direct access to as few instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Before Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;After Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and enhanced readability of code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render :action =&amp;gt; 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(:user_id =&amp;gt; @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(action: AuthHelper::get_home_action(session[:user]), controller: AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render action: 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(user_id: @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Use of Routing Helpers==&lt;br /&gt;
Routing helpers are a simpler alternative to the otherwise complex hard coded URLs which reduce the readability of the code.Routing helpers allow us to declare possible common routes for a given controller. Routing helpers have been implemented since they maintain consistency even if changes are made to the routing paths. &lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        get_role&lt;br /&gt;
        if @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
          render :action =&amp;gt; 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
        redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        role=get_role&lt;br /&gt;
        if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
          render action: 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to users_path  #Replaced URL with routing helper &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
      redirect_to users_path  #Replaced URL with routing helper&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Replace find_by_.. with where in querying==&lt;br /&gt;
Rails 4 conventions dictate the use of 'where()' over the use of 'find_by_...' methods while querying ActiveRecords. The code has been refactored to replace the usages of find_by.. with where().&lt;br /&gt;
&lt;br /&gt;
Before Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89630</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89630"/>
		<updated>2014-10-25T04:47:48Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Replace find_by_.. by where in querying */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects, and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project Expertiza with main focus of Refactoring the Users Controller. &lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes,removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller action as it indicates towards increased coupling. We want to reduce the coupling as much as possible and view should have direct access to as few instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Before Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;After Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and enhanced readability of code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render :action =&amp;gt; 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(:user_id =&amp;gt; @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(action: AuthHelper::get_home_action(session[:user]), controller: AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render action: 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(user_id: @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Use of Routing Helpers==&lt;br /&gt;
Routing helpers are a simpler alternative to the otherwise complex hard coded URLs which reduce the readability of the code.Routing helpers allow us to declare possible common routes for a given controller. Routing helpers have been implemented since they maintain consistency even if changes are made to the routing paths. &lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        get_role&lt;br /&gt;
        if @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
          render :action =&amp;gt; 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
        redirect_to :action =&amp;gt; 'list' &lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        role=get_role&lt;br /&gt;
        if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
          render action: 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to users_path  #Replaced URL with routing helper &lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
      redirect_to users_path  #Replaced URL with routing helper&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Replace find_by_.. by where in querying==&lt;br /&gt;
Rails 4 conventions dictate the use of 'where()' over the use of 'find_by_...' methods while querying ActiveRecords. The code has been refactored to replace the usages of find_by.. with where().&lt;br /&gt;
&lt;br /&gt;
Before Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89627</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89627"/>
		<updated>2014-10-25T04:43:08Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects, and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project Expertiza with main focus of Refactoring the Users Controller. &lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes,removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller action as it indicates towards increased coupling. We want to reduce the coupling as much as possible and view should have direct access to as few instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Before Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;After Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and enhanced readability of code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render :action =&amp;gt; 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(:user_id =&amp;gt; @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 redirect_to(action: AuthHelper::get_home_action(session[:user]), controller: AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 render action: 'show'&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 AssignmentQuestionnaire.create(user_id: @user.id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Use of Routing Helpers==&lt;br /&gt;
Routing helpers are a simpler alternative to the otherwise complex hard coded URLs which reduce the readability of the code.Routing helpers allow us to declare possible common routes for a given controller. Routing helpers have been implemented since they maintain consistency even if changes are made to the routing paths. &lt;br /&gt;
&lt;br /&gt;
Before Refactoring:&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.find_by_name(params[:user][:name])&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        get_role&lt;br /&gt;
        if @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
          render :action =&amp;gt; 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to :action =&amp;gt; 'list'&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
        redirect_to :action =&amp;gt; 'list'&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
After Refactoring&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def show_selection&lt;br /&gt;
      @user = User.where(name: params[:user][:name]).take&lt;br /&gt;
      if @user != nil&lt;br /&gt;
        role=get_role&lt;br /&gt;
        if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
          render action: 'show'&lt;br /&gt;
        else&lt;br /&gt;
          flash[:note] = 'The specified user is not available for editing.'&lt;br /&gt;
          redirect_to users_path  #Replaced URL with routing helper&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        flash[:note] = params[:user][:name]+' does not exist.'&lt;br /&gt;
        redirect_to users_path  #Replaced URL with routing helper&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Replace find_by_.. by where in querying==&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89624</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89624"/>
		<updated>2014-10-25T04:32:00Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Instance Variable Reductions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects, and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project Expertiza with main focus of Refactoring the Users Controller. &lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes,removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller action as it indicates towards increased coupling. We want to reduce the coupling as much as possible and view should have direct access to as few instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Before Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;After Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and enhanced readability of code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89623</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89623"/>
		<updated>2014-10-25T04:29:47Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects, and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project Expertiza with main focus of Refactoring the Users Controller. &lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes,removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller action as it indicates towards increased coupling. We want to reduce the coupling as much as possible and view should have direct access to as little instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Before Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;After Refactoring&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and enhanced readability of code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89622</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89622"/>
		<updated>2014-10-25T04:24:42Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Instance Variable Reductions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects, and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project Expertiza with main focus of Refactoring the Users Controller. &lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Classes :&amp;lt;/b&amp;gt; users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What it does : &amp;lt;/b&amp;gt;Manage Users i.e.search and list users, create new user, edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;b&amp;gt;What has to be changed : &amp;lt;/b&amp;gt;&lt;br /&gt;
* Modify methods to conform to RESTful style &lt;br /&gt;
* Reducing the number of instance variables per action to one&lt;br /&gt;
* Code cleanup by using string interpolation instead of concatenation, replacing '==' with eql? and :key =&amp;gt;'value' with key: 'value', modifying declarations of Arrays and Hashes,removing commented out code&lt;br /&gt;
* Use of routing helpers instead of hardcoded URLs&lt;br /&gt;
* Replace find_by with where to follow Rails 4.0 conventions&lt;br /&gt;
&lt;br /&gt;
==Modification to Existing Code==&lt;br /&gt;
&lt;br /&gt;
===RESTful style implementation===&lt;br /&gt;
* Modifications to users_controller.rb : The purpose of the index method in Users Controller is to list all registered users. The list method was called from the index method to list all users. This implementation did not conform to RESTful guidelines. Hence, we refactored the list method in users controller to index. Further, we refactored all the references of list method in UserControllers, Users views, Users tests and routes.rb to index method.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      list&lt;br /&gt;
      render :action =&amp;gt; 'list'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  #for displaying the list of users&lt;br /&gt;
  def list&lt;br /&gt;
    user = session[:user]&lt;br /&gt;
    role = Role.find(user.role_id)&lt;br /&gt;
    all_users = User.order('name').where( ['role_id in (?) or id = ?', role.get_available_roles, user.id])&lt;br /&gt;
&lt;br /&gt;
    letter = params[:letter]&lt;br /&gt;
    session[:letter] = letter&lt;br /&gt;
    if letter == nil&lt;br /&gt;
      letter = all_users.first.name[0,1].downcase&lt;br /&gt;
    end&lt;br /&gt;
    logger.info &amp;quot;#{letter}&amp;quot;&lt;br /&gt;
    @letters = Array.new&lt;br /&gt;
&lt;br /&gt;
    @per_page = 1&lt;br /&gt;
&lt;br /&gt;
    # Check if the &amp;quot;Show&amp;quot; button for pagination is clicked&lt;br /&gt;
    # If yes, set @per_page to the value of the selection dropdown&lt;br /&gt;
    # Else, if the request is from one of the letter links on the top&lt;br /&gt;
    # set @per_page to 1 (25 names per page).&lt;br /&gt;
    # Else, set @per_page to the :num_users param passed in from&lt;br /&gt;
    # the will_paginate method from the 'pagination' partial.&lt;br /&gt;
    if params[:paginate_show]&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    elsif params[:from_letter]&lt;br /&gt;
      @per_page = 1&lt;br /&gt;
    else&lt;br /&gt;
      @per_page = params[:num_users]&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    # Get the users list to show on current page&lt;br /&gt;
    @users = paginate_list(role, user.id, letter)&lt;br /&gt;
&lt;br /&gt;
    @letters = ('A'..'Z').to_a&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;
 #for displaying the list of users&lt;br /&gt;
  def index&lt;br /&gt;
    if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
      redirect_to(:action =&amp;gt; AuthHelper::get_home_action(session[:user]), :controller =&amp;gt; AuthHelper::get_home_controller(session[:user]))&lt;br /&gt;
    else&lt;br /&gt;
      #list method's implementation&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Instance Variable Reductions===&lt;br /&gt;
It is a bad practice to have more than one instance variables in a controller action as it indicates towards increased coupling. We want to reduce the coupling as much as possible and view should have direct access to as little instance variables as possible. Helper methods should be defined in controllers through which  the view can access variables of the controller class. The code has been refactored to make use of helper methods for the instance variables in index action.&lt;br /&gt;
&lt;br /&gt;
Before Refactoring&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            @role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            @role = Role.new(:id =&amp;gt; nil, :name =&amp;gt; '(none)')&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to @role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; @role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring&lt;br /&gt;
&lt;br /&gt;
users_controller.rb&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def get_role&lt;br /&gt;
          if @user &amp;amp;&amp;amp; @user.role_id&lt;br /&gt;
            role = Role.find(@user.role_id)&lt;br /&gt;
          elsif @user&lt;br /&gt;
            role = Role.new(id: nil, name: '(none)')&lt;br /&gt;
          end&lt;br /&gt;
          return role&lt;br /&gt;
        end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
show.html.erb&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Role:&amp;lt;/th&amp;gt;&lt;br /&gt;
    &amp;lt;td&amp;gt;&amp;lt;%= link_to get_role.name, :controller =&amp;gt; 'roles',&lt;br /&gt;
      :action =&amp;gt; 'show', :id =&amp;gt; get_role.id %&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;
  &amp;lt;/tr&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Code Cleanup===&lt;br /&gt;
Code cleanup in the controller so that the code conforms closely to Rails conventions and enhanced readability of code.&lt;br /&gt;
* Replaced String concats with #{} in paginate_list&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#paginate_list&lt;br /&gt;
 search_filter = letter + '%'&lt;br /&gt;
 search_filter = '%' + letter + '%'&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;
#paginate_list&lt;br /&gt;
 search_filter = &amp;quot;#{letter}%&amp;quot;&lt;br /&gt;
 search_filter = &amp;quot;%#{letter}%&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced '==' with eql?&lt;br /&gt;
Before Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role? == &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 letter == nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 @role.parent_id == nil || @role.parent_id &amp;lt; (session[:user]).role_id || @user.id == (session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name == &amp;quot;Instructor&amp;quot; or @user.role.name == &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role? == &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
  if @search_by == '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After Refactoring :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#index&lt;br /&gt;
 if (current_user_role.eql? &amp;quot;Student&amp;quot;)&lt;br /&gt;
 ...&lt;br /&gt;
 if letter.eql? nil&lt;br /&gt;
&lt;br /&gt;
#show_selection&lt;br /&gt;
 if role.parent_id.eql? nil || role.parent_id &amp;lt; (session[:user]).role_id || @user.id.eql?(session[:user]).id&lt;br /&gt;
&lt;br /&gt;
#show&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#create&lt;br /&gt;
 if @user.role.name.eql? &amp;quot;Instructor&amp;quot; or @user.role.name.eql? &amp;quot;Administrator&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#keys&lt;br /&gt;
 if (params[:id].nil?) || ((current_user_role.eql? &amp;quot;Student&amp;quot;) &amp;amp;&amp;amp;  (session[:user].id != params[:id].to_i))&lt;br /&gt;
&lt;br /&gt;
#paginate_list&lt;br /&gt;
 if @search_by.eql? '1'  #search by user name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Replaced :key =&amp;gt;'value' with key: 'value'&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89606</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89606"/>
		<updated>2014-10-25T00:34:33Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects, and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project Expertiza with main focus of Refactoring the Users Controller. &lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
Classes : users_controller.rb&amp;lt;br&amp;gt;&lt;br /&gt;
What it does : Manage Users i.e.search and list users,create new user,edit/update existing users, delete users.&amp;lt;br&amp;gt;&lt;br /&gt;
What has to be changed : Modify methods to conform to RESTful style. Refactor code such that it follows Ruby Conventions for Collection Objects like Arrays and Hashes.&lt;br /&gt;
&amp;lt;references/&amp;gt;&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89605</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89605"/>
		<updated>2014-10-25T00:33:22Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects, and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project Expertiza with main focus of Refactoring the Users Controller. &lt;br /&gt;
&lt;br /&gt;
==Project Description==&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Users are mapped to different roles like super-admin, admin, instructor, teaching assistant and student with each role having different access permissions. The Manage Users module can be accessed by roles other than the student. It provides users with the functionality to search other users based on keywords like username, email, etc. New user can be created and existing user information and role can be updated.&lt;br /&gt;
&lt;br /&gt;
Classes : users_controller.rb&lt;br /&gt;
What it does : Manage Users i.e.search and list users,create new user,edit/update existing users, delete users.&lt;br /&gt;
What has to be changed : Modify methods to conform to RESTful style. Refactor code such that it follows Ruby Conventions for Collection Objects like Arrays and Hashes.&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89604</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89604"/>
		<updated>2014-10-25T00:05:25Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects, and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project Expertiza with main focus of Refactoring the Users Controller. &lt;br /&gt;
&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Each user is mapped to different roles thus having access to restricted functionality based on associated role. &lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89603</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89603"/>
		<updated>2014-10-25T00:04:40Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' Retrieved from http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects, and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
As a part of the coursework of Object Oriented Design and Development, we were expected to refactor the funtionality of some modules of Expertiza. This wiki provides an insight into our contributions to the Open Source Software project Expertiza with main focus of Refactoring the Users Controller. &lt;br /&gt;
&lt;br /&gt;
The Users Controller deals with managing activities peripheral to the User registered with Expertiza. Each user is mapped to different roles thus having access to restricted functionality based on associated role. &lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89602</id>
		<title>CSC/ECE 517 Fall 2014/oss E1465 oak</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/oss_E1465_oak&amp;diff=89602"/>
		<updated>2014-10-24T23:56:25Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: Created page with &amp;quot;=Expertiza - Refactoring UsersController=  __TOC__  ==Introduction== Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' Retrieved from http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref...&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Expertiza - Refactoring UsersController=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' Retrieved from http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application available to both students and professors. The Expertiza project is a system to create reusable learning objects through peer review. Expertiza supports team projects, and the submission of almost any document type, including URLs and wiki pages. Students can keep a track of their assignments, teammates and can conduct peer reviews on diverse topics and projects. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
This wiki provides an insight into our contributions to the Open Source Software project Expertiza with main focus refactoring the users controller. Reporting score functionality is handled by controllers/grades_controller.rb and rendered by views/grades/_view_my_score.html.erb. Improved User Interface using JQuery is our contribution to Expertiza. This new elegant UI uses tabs instead of tables which makes it look elegant and renders faster. Subtle code and design challenges, changes and the motivation to implement this design have been explained further.&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88248</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=88248"/>
		<updated>2014-09-24T23:59:14Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Simple Explanation */&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&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Object-relational_mapping&amp;lt;/ref&amp;gt;==&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>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88227</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=88227"/>
		<updated>2014-09-24T23:35:43Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Sequel */&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==&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>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88226</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=88226"/>
		<updated>2014-09-24T23:34:16Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Active Recordshttp://guides.rubyonrails.org/active_record_basics.html */&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 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>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88224</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=88224"/>
		<updated>2014-09-24T23:31:37Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Introductionhttp://en.wikipedia.org/wiki/Object-relational_mapping Object Relational Mapping */&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&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>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88221</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=88221"/>
		<updated>2014-09-24T23:29:26Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Active Records */&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>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88219</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=88219"/>
		<updated>2014-09-24T23:27:15Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Disadvantageshttp://www.techopedia.com/definition/24200/object-relational-mapping--orm */&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==&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>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88216</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=88216"/>
		<updated>2014-09-24T23:26:23Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Features */&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&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>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88215</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=88215"/>
		<updated>2014-09-24T23:23:25Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Object Relational Mapping */&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== &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>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88214</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=88214"/>
		<updated>2014-09-24T23:23:03Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: &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;(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>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88212</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=88212"/>
		<updated>2014-09-24T23:19:54Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* References */&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;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88211</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=88211"/>
		<updated>2014-09-24T23:17:58Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Disadvantageshttp://www.techopedia.com/definition/24200/object-relational-mapping--orm */&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;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88209</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=88209"/>
		<updated>2014-09-24T23:17:41Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Disadvantages */&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;&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;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88206</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=88206"/>
		<updated>2014-09-24T23:17:17Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Features */&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 ==&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;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88205</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=88205"/>
		<updated>2014-09-24T23:16:47Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: &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 ==&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;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88203</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=88203"/>
		<updated>2014-09-24T23:15:18Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Advantages */&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;
&amp;lt;ref&amp;gt;http://www.techopedia.com/definition/24200/object-relational-mapping--orm&amp;lt;/ref&amp;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;
# [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;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88200</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=88200"/>
		<updated>2014-09-24T23:05:30Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Further Reading */&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;
# [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;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88199</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=88199"/>
		<updated>2014-09-24T23:05:19Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Further Reading */&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;
# [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;/div&gt;</summary>
		<author><name>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88197</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=88197"/>
		<updated>2014-09-24T22:58:45Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: &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;
&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>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88194</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=88194"/>
		<updated>2014-09-24T22:52:51Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Further Reading */&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;
==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;
==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>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88193</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=88193"/>
		<updated>2014-09-24T22:52:29Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Further Reading */&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;
==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;
==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>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88192</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=88192"/>
		<updated>2014-09-24T22:50:54Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: &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;
==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;
==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]&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>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88189</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=88189"/>
		<updated>2014-09-24T22:24:53Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: &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;
==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;
==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://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>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=88188</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=88188"/>
		<updated>2014-09-24T22:22:52Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Sequel */&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;
==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;
==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>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=87183</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=87183"/>
		<updated>2014-09-19T23:27:42Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Overview */&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;
==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>Knimgao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2014/ch1a_25_ks&amp;diff=86420</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=86420"/>
		<updated>2014-09-18T04:04:30Z</updated>

		<summary type="html">&lt;p&gt;Knimgao: /* Squeel */&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;
&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>Knimgao</name></author>
	</entry>
</feed>