CSC/ECE 517 Spring 2015/oss E1501 YWS: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
 
(45 intermediate revisions by 2 users not shown)
Line 1: Line 1:
'''E1501: Refactoring Assignments.rb'''
==E1501: Refactoring Assignments.rb==
This page is about an open source project based on Expertiza OSS. This project aims to refactor assignment.rb which is the largest class in Expertiza. It also aims to refactor other snippets which does not follow the Ruby style guidelines.
===Refactoring===
<ref>[http://refactoring.com/ Refactoring]</ref><b>Refactoring</b> is a technique to alter the internal structure of the code without affecting the external behaviour.
It is used for:


This page provides information about a project which aims to refactor Assignment.rb file present in Expertiza OSS.
* Programs that are difficult to read;
* Programs that does not follow the language specific guidelines;
* Programs that has high coupling;


'''Introduction to Expertiza'''<br>
=== Introduction to Expertiza ===


[http://expertiza.ncsu.edu/ Expertiza] is an open source project developed using the [http://rubyonrails.org/ Ruby on Rails] platform. It provides features like team assignments, peer review, submission of projects, grading etc. The code can be cloned from [https://github.com/expertiza/expertiza GitHub]. This application provides an efficient way to manage assignments, grades and reviews, which makes the process easier and faster when the class strength is large.  
<ref>[http://expertiza.ncsu.edu/ Expertiza]</ref>Expertiza is an open source project developed using the [http://rubyonrails.org/ Ruby on Rails] platform. It provides features like team assignments, peer review, submission of projects, grading etc. The code can be cloned and modified from [https://github.com/expertiza/expertiza GitHub]. This application provides an efficient way to manage assignments, grades and reviews.


Assignment.rb is a file which contains the assignment model and the related functionality. It also contains the score module which is refactored to make the file more clean and easy to read.
Assignment.rb is the largest class in Expertiza, comprising 1105 lines of code which contains the assignment model and the related functionalities. It also contains the score module which is refactored to make the file more clean and easy to read.


__TOC__
__TOC__
Line 19: Line 26:


'''What they do'''
'''What they do'''
<p>Assignment.rb along with the controller file is responsible for creating and editing the assignments. The file also contains the functions responsible for grading.</p>
<p>Assignment.rb along with the controller file is responsible for creating and editing the assignments. The file also contains methods which calculates the student scores. The assignment and scoring modules are very tightly bound which can be grouped into smaller, more manageable classes.</p>


'''What needs to be done:'''
'''What needs to be done:'''
<p> The assignment model needed a refactoring as it contains some modules which were responsible for generating assignment scores. Moreover, the querying module was database dependent which was made database independent. There were many function names and code lines which were not following the ruby guidelines. They were changed to more ruby like coding style. </p>
<p>  
*The assignment model needs refactoring as it contains some modules which are responsible for generating assignment scores;
*Moreover, the querying module is database dependent which should be made database independent;
*There are many function names and code lines which does not follow the ruby guidelines. They should be changed to more ruby like coding style; </p>




Line 29: Line 39:
== Instance 1 : Refactoring the Assignment.rb ==
== Instance 1 : Refactoring the Assignment.rb ==


===Creation of separate model scorable.rb===
===Creation of separate module scorable.rb===
<ref>[http://guides.rubyonrails.org/active_record_basics.html ActiveRecord]</ref>ActiveRecord concern is a pattern introduced in Rails 4.1 to separate the heavy loading done by models. It is recommended that models should be fat and should contain the business logic. This is leads to models getting too coupled. ActiveRecord Concerns solves this problem. Methods which can be logically put together are added in a <ref>[http://rubylearning.com/satishtalim/modules_mixins.html Module/Mixins]</ref> module/mixin. This mixin is then included in the main model. The mixin can be reused by any other model if required. This makes the code align with Rails philosophy of DRY. In this case all methods related to 'scores' were collaborated together and put inside the mixin scorable. 
There are many methods which are not directly related to assignments. These methods are responsible for generating the scores and related functions. These methods are:
There are many methods which are not directly related to assignments. These methods are responsible for generating the scores and related functions. These methods are:
<p>1.get_scores</p>
*get_scores;
<p>2.get_max_score_possible</p>
*get_max_score_possible;
<p>3.compute_reviews_hash</p>
*compute_reviews_hash;
<p>4.get_average_score</p>
*get_average_score;
All these methods are taken out of assignment.rb and pushed into a new file "scorable.rb". This made score generation a separate module and the dependency of scores on assignments have been reduced significantly.  
 
<b>view:assignments/edit.html.erb</b><br>
All these methods are taken out of assignment.rb and pushed into a new file "scorable.rb". This made score generation a separate module and the dependency of scores on assignments reduced significantly. The pull request can be viewed <span class="plainlinks"> [https://github.com/yatish27/expertiza/commit/ddbd575e6695e8c6b4b6fff8c8aaf814a3981773 here]</span>.
This view contains all the tabs to display like general,rubrics,review_strategy, topics which are related to the selected assignment. tabs-5 is the topics tab which we are interested in.
 
== Instance 2 : Ruby idiomatic==
 
===Make assignment.rb more Ruby like===
There were many instances where the coding was not like ruby like. The ruby community believes in small and well readable code. The code was refactored to be more readable. Many changes were done to the structure of the code to make it more Ruby like. Changes such as removing the return statements, writing .each instead of "for loop", adding a "?" to name of methods if they return boolean values, indentations and naming conventions were improved. Few of the examples are shown below in raw form as well as Github screenshots:
<p>
[[File:Refac.JPG|center]]
</p>
This refactoring example makes the snippet small and easy to read. It also introduces more Ruby style terms like select and processes like piping instructions.
'''Before Change'''
<pre>
<pre>
  <div id="tabs-3">
quiz_response_mappings.each do |qmapping|
        <%= render 'assignments/edit/review_strategy' %>
   if qmapping.response
   </div>
    quiz_responses << qmapping.response
  <div id="tabs-4">
   end
        <%= render 'assignments/edit/due_dates' %>
end
   </div>
  <div id="tabs-5">
        <%= render 'assignments/edit/add_signup_topics' %>
  </div>
</pre>
</pre>


===After Changes===
'''After Change'''
We have redundant code in two methods so we merged add_signup_topics_staggered and add_signup_topics into add_signup_topics. The action calls single method for both type of assignments and renders views based on condition of staggered or non-staggered assignment.
<pre>
quiz_responses = quiz_response_mappings.select{ |qmapping| qmapping.response }.map(&:response)
</pre>


<pre>
'''Before Change'''
  <div id="tabs-3">
<pre>
        <%= render 'assignments/edit/review_strategy' %>
total = 0
  </div>
self.questionnaires.each { |questionnaire| total += questionnaire.get_weighted_score(self, scores) }
  <div id="tabs-4">
total
        <%= render 'assignments/edit/due_dates' %>
  </div>
  <div id="tabs-5">
        <%= render '/sign_up_sheet/add_signup_topcis.html' %>
  </div>
</pre>
</pre>


=== Refactoring view code into relevant views ===
'''After Change'''
There were no edit/delete links to edit/delete a topic in the instructor view. These had to be conditionally added based on the role of the currently logged in user. This was to prevent students from editing/deleting topics and to keep instructors from signing up for a topic. This was implemented as follows.
<pre>
self.questionnaires.inject(0) { |total, questionnaire| total + questionnaire.get_weighted_score(self, scores) }
</pre>


===Adding Edit/Delete functionality to topics tab===
== Instance 3 : Addition of ActiveRecord like Query==
ActiveRecord provides a layer on top database. Hence if no MYSQL specific query is used in the code it very simple to change the database without changing the code. Using Ruby hash for query rather than raw SQL also helps in keeping the code clean.
The queries where changed to function more like active record query. This made the queries database independent and more user friendly.


The current expertiza project had two views to display the Actions column in the topics table. These were _reserve_topics.html.erb and _actions.html. The first one was displaying the signup button for the student and the latter was displaying the bookmarks and rendering the _reserve_topics.html.erb after the bookmarks. On top of this we had to add the edit/delete links for the instructor. A refactor was called for. We decided to create a _all_actions.html.erb partial which had the responsibility to display the relevant actions depending upon the role of the currently logged in user. This helped us remove the separate partial to render actions pertaining to a student, namely _reserve_topics.html.erb . Also the _actions.html.erb only took care of displaying the bookmark links rather than dealing with both bookmarks and actions.
'''Before Change'''
<pre>
  DueDate.where( ['assignment_id = ? and deadline_type_id >= ?', self.id, 7]).due_at
</pre>


<b>partial_view:_all_actions,html.erb</b>
'''After Change'''
<pre>
<pre>
<% if ['Instructor', 'Teaching Assistant', 'Administrator', 'Super-Administrator'].include? current_user_role?.name %>
  DueDate.where(assignment_id: self.id, deadline_type_id: 7).due_at
    <td align="center">
      <%= link_to image_tag('edit_icon.png', :border => 0, :title => 'Edit Topic', :align => 'middle'), :controller=>'sign_up_sheet', :action=> 'edit', :id => topic.id %>
      <%= link_to image_tag('delete_icon.png', :border => 0, :title => 'Delete Topic', :align => 'middle'), sign_up_sheet_path(topic.id), method: :delete, data: {confirm: 'Are you sure?'} %>
<%elsif @show_actions %>
    ...
    #Render signup button for student here. The @show_actions will be true if this partial is navigated from the SignupSheetController which is accessible only to students.
</pre>
</pre>


== Instance 4: Ruby style guide ==
<ref>[https://github.com/bbatsov/rubocop Rubocop]</ref>`Rubocop` was used to check the ruby style guide violations. Most of the Ruby style guide violations in assignment.rb class were fixed.
<p>
[[File:Refac1.JPG|center]]
</p>


== Case 2 : Cleaning up unused code ==
== Instance 5 : Changing <ref>[http://bundler.io/gemfile.html Gemfile]</ref>Gemfile==
The Refactors mentioned above enable us to delete unused partials namely:


*assignments controller partials :
*Version of gem "EventMachine" was updated as earlier version was incompatible with ruby version 2.2.0. The version was changed from 1.0.3 to 1.0.7.;
**_add_signup_topics.html.erb
*One more gem <ref>[https://github.com/evrone/quiet_assets Quite_assets]</ref> "quite_assets" was added to avoid unnecessary log creation of the asset request. It mutes the asset pipeline log messages. This gem is very helpful during  development.;
**_reserve_topic.html.erb


*signup_sheet_controller partials :
* Clean up tests: Few of the controller tests were not in the correct order. We changed them to the right order.  
**_reserve_topic.html.erb
<br>


=Steps to verify changes=
=Steps to verify changes=
 
* Feature change was not in the scope of the project. The changes are checking bad code smells and fixing them. The way to verify the changes is to make sure that it works as it was previously. Also, please have a look at the pull request for all the refactor details. You can pull the code with refactored file <span class="plainlinks"> [https://github.com/yatish27/expertiza here]</span>.


=See Also=
=See Also=
#[https://github.com/expertiza/expertiza Expertiza on GitHub]
#[https://github.com/expertiza/expertiza Expertiza on GitHub]
#[https://github.com/itsmylifesoham/expertiza GitHub Project Repository Fork]
#[https://github.com/expertiza/expertiza/pull/510 Expertiza Pull request]
#[http://expertiza.ncsu.edu/ The live Expertiza website]
#[http://expertiza.ncsu.edu/ The live Expertiza website]
#[http://152.46.18.5:3000/ VCL link] - This might not be available after Nov. 2014
#[http://wikis.lib.ncsu.edu/index.php/Expertiza Expertiza project documentation wiki]
#[http://wikis.lib.ncsu.edu/index.php/Expertiza Expertiza project documentation wiki]
#[https://docs.google.com/document/d/1FZCL9KWSdVNsX9BowuZ3gxbCOJoiWX-GVLctSZei3No The OSS project requirements doc (Fall 2014 - Expertiza)]


= References=
= References=
[http://expertiza.ncsu.edu/ Expertiza]<br>
<references/>
[http://en.wikipedia.org/wiki/Code_refactoring Code Refactoring]<br>
[http://en.wikipedia.org/wiki/Code_smell Code smell]

Latest revision as of 01:16, 24 March 2015

E1501: Refactoring Assignments.rb

This page is about an open source project based on Expertiza OSS. This project aims to refactor assignment.rb which is the largest class in Expertiza. It also aims to refactor other snippets which does not follow the Ruby style guidelines.

Refactoring

<ref>Refactoring</ref>Refactoring is a technique to alter the internal structure of the code without affecting the external behaviour. It is used for:

  • Programs that are difficult to read;
  • Programs that does not follow the language specific guidelines;
  • Programs that has high coupling;

Introduction to Expertiza

<ref>Expertiza</ref>Expertiza is an open source project developed using the Ruby on Rails platform. It provides features like team assignments, peer review, submission of projects, grading etc. The code can be cloned and modified from GitHub. This application provides an efficient way to manage assignments, grades and reviews.

Assignment.rb is the largest class in Expertiza, comprising 1105 lines of code which contains the assignment model and the related functionalities. It also contains the score module which is refactored to make the file more clean and easy to read.

Problem Statement

Classes involved:

assignment.rb
scorable.rb
Gemfile
schema.rb

What they do

Assignment.rb along with the controller file is responsible for creating and editing the assignments. The file also contains methods which calculates the student scores. The assignment and scoring modules are very tightly bound which can be grouped into smaller, more manageable classes.

What needs to be done:

  • The assignment model needs refactoring as it contains some modules which are responsible for generating assignment scores;
  • Moreover, the querying module is database dependent which should be made database independent;
  • There are many function names and code lines which does not follow the ruby guidelines. They should be changed to more ruby like coding style;

Re-factored Instances

Instance 1 : Refactoring the Assignment.rb

Creation of separate module scorable.rb

<ref>ActiveRecord</ref>ActiveRecord concern is a pattern introduced in Rails 4.1 to separate the heavy loading done by models. It is recommended that models should be fat and should contain the business logic. This is leads to models getting too coupled. ActiveRecord Concerns solves this problem. Methods which can be logically put together are added in a <ref>Module/Mixins</ref> module/mixin. This mixin is then included in the main model. The mixin can be reused by any other model if required. This makes the code align with Rails philosophy of DRY. In this case all methods related to 'scores' were collaborated together and put inside the mixin scorable. There are many methods which are not directly related to assignments. These methods are responsible for generating the scores and related functions. These methods are:

  • get_scores;
  • get_max_score_possible;
  • compute_reviews_hash;
  • get_average_score;

All these methods are taken out of assignment.rb and pushed into a new file "scorable.rb". This made score generation a separate module and the dependency of scores on assignments reduced significantly. The pull request can be viewed here.

Instance 2 : Ruby idiomatic

Make assignment.rb more Ruby like

There were many instances where the coding was not like ruby like. The ruby community believes in small and well readable code. The code was refactored to be more readable. Many changes were done to the structure of the code to make it more Ruby like. Changes such as removing the return statements, writing .each instead of "for loop", adding a "?" to name of methods if they return boolean values, indentations and naming conventions were improved. Few of the examples are shown below in raw form as well as Github screenshots:

This refactoring example makes the snippet small and easy to read. It also introduces more Ruby style terms like select and processes like piping instructions. Before Change

 quiz_response_mappings.each do |qmapping|
   if qmapping.response
     quiz_responses << qmapping.response
   end
 end

After Change

 quiz_responses = quiz_response_mappings.select{ |qmapping| qmapping.response }.map(&:response)

Before Change

 total = 0
 self.questionnaires.each { |questionnaire| total += questionnaire.get_weighted_score(self, scores) }
 total

After Change

 self.questionnaires.inject(0) { |total, questionnaire| total + questionnaire.get_weighted_score(self, scores) }

Instance 3 : Addition of ActiveRecord like Query

ActiveRecord provides a layer on top database. Hence if no MYSQL specific query is used in the code it very simple to change the database without changing the code. Using Ruby hash for query rather than raw SQL also helps in keeping the code clean. The queries where changed to function more like active record query. This made the queries database independent and more user friendly.

Before Change

  DueDate.where( ['assignment_id = ? and deadline_type_id >= ?', self.id, 7]).due_at

After Change

  DueDate.where(assignment_id: self.id, deadline_type_id: 7).due_at

Instance 4: Ruby style guide

<ref>Rubocop</ref>`Rubocop` was used to check the ruby style guide violations. Most of the Ruby style guide violations in assignment.rb class were fixed.

Instance 5 : Changing <ref>Gemfile</ref>Gemfile

  • Version of gem "EventMachine" was updated as earlier version was incompatible with ruby version 2.2.0. The version was changed from 1.0.3 to 1.0.7.;
  • One more gem <ref>Quite_assets</ref> "quite_assets" was added to avoid unnecessary log creation of the asset request. It mutes the asset pipeline log messages. This gem is very helpful during development.;
  • Clean up tests: Few of the controller tests were not in the correct order. We changed them to the right order.

Steps to verify changes

  • Feature change was not in the scope of the project. The changes are checking bad code smells and fixing them. The way to verify the changes is to make sure that it works as it was previously. Also, please have a look at the pull request for all the refactor details. You can pull the code with refactored file here.

See Also

  1. Expertiza on GitHub
  2. Expertiza Pull request
  3. The live Expertiza website
  4. Expertiza project documentation wiki

References

<references/>