E1908 signupsheet: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
 
(10 intermediate revisions by 2 users not shown)
Line 8: Line 8:


===About Expertiza===
===About Expertiza===
[http://expertiza.ncsu.edu/Expertiza] is an open source project dependent on [http://rubyonrails.org/Ruby on Rails] structure. Expertiza enables the teacher to make new assignments and alter new or existing assignments. It additionally enables the educator to make a rundown of subjects the students can agree to accept. Students can shape groups in Expertiza to chip away at different undertakings and projects. Students can likewise peer audit other students' entries. Expertiza underpins accommodation crosswise over different record types, including the URLs and wiki pages.


[http://expertiza.ncsu.edu/ Expertiza] is an open source project based on [http://rubyonrails.org/ Ruby on Rails] framework. Expertiza allows the instructor to create new assignments and customize new or existing assignments. It also allows the instructor to create a list of topics the students can sign up for. Students can form teams in Expertiza to work on various projects and assignments. Students can also peer review other students' submissions. Expertiza supports submission across various document types, including the URLs and wiki pages.


===Problem Statement===
===Problem Statement===
Line 18: Line 18:
* Rectified several unwanted if-else conditions in methods and optimized the code.
* Rectified several unwanted if-else conditions in methods and optimized the code.
* Refactored all instance variables and removed unnecessarily defined variables.
* Refactored all instance variables and removed unnecessarily defined variables.
*  
* Removed certain unwanted flash messages that occur for some user actions.
* Added missing CRUD methods to Versions Controller
* Included comments for functionalities throughout for better understanding.
* Added RSPEC test cases for testing changes done in Versions Controller


===About Versions Controller===
===About Sign-up sheet Controller===
This class manages different versions of reviews. If a reviewer reviews a submission, and after that, the author revises the submission, the next time the reviewer does a review (s)he will create a new version. Sometimes it’s necessary to find the current version of a review; sometimes it’s necessary to find all versions. Similarly, a user may want to delete the current version of a review, or all versions of a review. Pagination of versions helps the user to view a subset of versions at a time. Considering the huge number of versions in the system, it is very useful to have a pagination mechanism and a filtering mechanism which can be applied on the whole set of versions. The idea is to display the versions in an ordered, comprehensible and logical manner. In Expertiza the gem ‘will_paginate’ is used to achieve pagination.
Sign-up sheet controller contains all functions related to management of the signup sheet for an assignment function to add new topics to an assignment, edit properties of a particular topic, delete a topic, etc are included here.


===Current Implementation===


=====Issues and Fixes=====


=====Functionality=====
* '''Problem 1''': Create method has an if-else condition determining if create or update should be called. Create method should not be responsible for calling update. Identify why the if-else condition exists. The if-else condition exists because the current implementation calls update if a signup sheet with the same name already exists.  
* Any user irrespective of his/ her privileges can view all the versions.
* '''Solution''': Rectified this method by removing the call to update and flashing an error instead.
::The versions which a particular user can view should be restricted based on the privileges of the user. For instance, only a user with Administrator privileges should be able to view all the versions in the system. However, that is not the case now. Every user can view all the versions irrespective of whether the user is a student or an administrator.
<pre>
* Any user can delete any version
::The versions which a particular user can delete should be restricted based on the privileges of the user. For instance, a student should not be allowed to delete any version. According to the current implementation any user can delete any version in the system.
* Filtering of versions were restricted to the current user
::The filtering options on versions were restricted to the current user. Sometimes a user might want to view versions associated with other users. For instance, an instructor might want to view the list of versions created by a particular student. This is not possible with the current implementation.


=====Drawbacks and Solutions=====
if topic.nil?
* '''Problem 1''': The method paginate_list is doing more than one thing.
      setup_new_topic
::The method paginate_list was building a complex search criteria based on the input params, getting the list of versions from the Database matching this search criteria and then calling the Page API. All these tasks in a single method made it difficult to understand.
    else
      # update_existing_topic topic
      # Create must not be used for calling update. So replaced it with an error message
      flash[:error] = "The topic already exists."
    end
  end
 
</pre>
 
* '''Problem 2''': Update method has a plethora of instance variables defined before updating. These are not necessary (For e.g., look at update method of bookmarks_controller).
* '''Solution''': Refactored the variables not needed out.
<pre>
<pre>
# For filtering the versions list with proper search and pagination.
  def paginate_list(id, user_id, item_type, event, datetime)
    # Set up the search criteria
    criteria = ''
    criteria = criteria + "id = #{id} AND " if id && id.to_i > 0
    if current_user_role? == 'Super-Administrator'
      criteria = criteria + "whodunnit = #{user_id} AND " if user_id && user_id.to_i > 0
    end
    criteria = criteria + "whodunnit = #{current_user.try(:id)} AND " if current_user.try(:id) && current_user.try(:id).to_i > 0
    criteria = criteria + "item_type = '#{item_type}' AND " if item_type && !(item_type.eql? 'Any')
    criteria = criteria + "event = '#{event}' AND " if event && !(event.eql? 'Any')
    criteria = criteria + "created_at >= '#{time_to_string(params[:start_time])}' AND "
    criteria = criteria + "created_at <= '#{time_to_string(params[:end_time])}' AND "


    if current_role == 'Instructor' || current_role == 'Administrator'
      update_max_choosers @topic
      # @topic.category = params[:topic][:category]
      # @topic.topic_name = params[:topic][:topic_name]
      # @topic.micropayment = params[:topic][:micropayment]
      # @topic.description = params[:topic][:description]
      # @topic.link = params[:topic][:link]
      # @topic.save
      # Replaced all the above unnecessary variables and save with a single update call for all the parameters
      @topic.update_attributes(topic_identifier: params[:topic][:topic_identifier], category: params[:topic][:category], topic_name: params[:topic][:topic_name], micropayment: params[:topic][:micropayment], description: params[:topic][:description], link: params[:topic][:link])
</pre>
 
 
* '''Problem 3''': Destroy has a misleading else flash message.
* '''Solution''': Refactored the mislleading flash messages not needed out.
<pre>


  @topic.destroy
      undo_link("The topic: \"#{@topic.topic_name}\" has been successfully deleted. ")
    else
      # Replaced this flash[:error] = "The topic could not be deleted." with
      flash[:error] = "This topic could not be found." # error message mage more specific
     end
     end
    # changing the redirection url to topics tab in edit assignment view.
    redirect_to edit_assignment_path(params[:assignment_id]) + "#tabs-5"


    # Remove the last ' AND '
    criteria = criteria[0..-5]


    versions = Version.page(params[:page]).order('id').per_page(25).where(criteria)
    versions
  end
</pre>
</pre>
* '''Solution''': The implementation has been changed in such a way that the versions which a user is allowed to see depends on the privileges of the user. The approach we have taken is as follows:
**An administrator can see all the versions
**An instructor can see all the versions created by him and other users who are in his course or are participants in the assignments he creates.
**A TA can see all the versions created by him and other users who are in the course for which he/ she assists.
**A Student can see all the versions created by him/ her.
* '''Problem 2''': The search criteria created in the method paginate_list was difficult to comprehend.
::The code which builds the search criteria in the method paginate_list uses many string literals and conditions and is hardly intuitive. The programmer will have to spend some time to understand what the code is really doing.
* '''Solution''': The implementation has been changed. A student is not allowed to delete any versions now. Other types of users, for instance administrators, instructors and TAs are allowed to delete only the versions they are authorized to view.
* '''Problem 3''': The paginate method can be moved to a helper class.
::VersionsController is not the only component which require to paginate items. There are other components too. For instance, the UsersController has to paginate the list of users. Hence the Paginate method can be moved to a helper class which can be accessed by other components as well.
* '''Solution''': The filtering options has also been enhanced. The current user can now choose as part of the version search filter any user from a list of users if the current user is authorized to see the versions created by that user.


===New Implementation===
 
*The method paginate_list has been split into 2 methods now.
 
** BuildSearchCriteria – as the name suggests the sole purpose of this method is to build a search criteria based on the input search filters when the current user initiates a search in versions.
* '''Problem 4''': Add_signup_topics_staggered does not do anything.
** paginate_list – this method will call the paginate API.
* '''Solution''': Renamed participants variable to 'teams'.
:First the search criteria is built, then the criteria is applied to versions in the database to get all versions which matches the criteria and then the retrieved versions are paginated.
<pre>
<pre>
  # pagination.
# add_signup_topics_staggered calls add_signup_topics and does nothing else. So removed the following function.
  def paginate_list(versions)
def add_signup_topics_staggered
     paginate(versions, VERSIONS_PER_PAGE);
     add_signup_topics
   end
   end
</pre>


   def BuildSearchCriteria(id, user_id, item_type, event)
* '''Problem 5''': Several method names are renamed to be more intuitive.
    # Set up the search criteria
* '''Solution''': load_add_signup_topics is renamed to get_assignment_data and ad_info is renamed to get_ad.
    search_criteria = ''
<pre>
    search_criteria = search_criteria + add_id_filter_if_valid(id).to_s
   # Contains links that let an admin or Instructor edit, delete, view enrolled/waitlisted members for each topic
    if current_user_role? == 'Super-Administrator'
  # Also contains links to delete topics and modify the deadlines for individual topics. Staggered means that different topics can have different deadlines.
      search_criteria = search_criteria + add_user_filter_for_super_admin(user_id).to_s
  # def load_add_signup_topics(assignment_id) previously
     end
  def get_assignment_data(assignment_id)
    search_criteria = search_criteria + add_user_filter
     @id = assignment_id
     search_criteria = search_criteria + add_version_type_filter(item_type).to_s
     @sign_up_topics = SignUpTopic.where('assignment_id = ?', assignment_id)
     search_criteria = search_criteria + add_event_filter(event).to_s
     @slots_filled = SignUpTopic.find_slots_filled(assignment_id)
    search_criteria = search_criteria + add_date_time_filter
    search_criteria
  end
</pre>
</pre>
* The string literals and conditions in the method paginate_list were replaced with methods with intuitive names so that the programmer can understand the code more easily. We also removed an empty if clause and a redundant statement.
 
 
 
* '''Problem 6''': The list method is too long and is sparsely commented.
* '''Solution''': Added comments.
<pre>
<pre>
  def add_id_filter_if_valid (id)
    "id = #{id} AND " if id && id.to_i > 0
  end


   def add_user_filter_for_super_admin (user_id)
  # function to list all topics and bids to a participant
     "whodunnit = #{user_id} AND " if user_id && user_id.to_i > 0
   def list
  end
    @participant = AssignmentParticipant.find(params[:id].to_i)
     @assignment = @participant.assignment
    @slots_filled = SignUpTopic.find_slots_filled(@assignment.id)
    @slots_waitlisted = SignUpTopic.find_slots_waitlisted(@assignment.id)
    @show_actions = true
    @priority = 0
    @sign_up_topics = SignUpTopic.where(assignment_id: @assignment.id, private_to: nil)
    @max_team_size = @assignment.max_team_size
    team_id = @participant.team.try(:id)


  def add_user_filter
    # If the assignment supports bidding, add all the bids of an
     "whodunnit = #{current_user.try(:id)} AND " if current_user.try(:id) && current_user.try(:id).to_i > 0
    # individual or team to the list of signed topics
  end
     if @assignment.is_intelligent
      @bids = team_id.nil? ? [] : Bid.where(team_id: team_id).order(:priority)
      signed_up_topics = []
      @bids.each do |bid|
        sign_up_topic = SignUpTopic.find_by(id: bid.topic_id)
        signed_up_topics << sign_up_topic if sign_up_topic
      end
      signed_up_topics &= @sign_up_topics
      @sign_up_topics -= signed_up_topics
      @bids = signed_up_topics
    end


  def add_event_filter (event)
    @num_of_topics = @sign_up_topics.size
     "event = '#{event}' AND " if event && !(event.eql? 'Any')
    @signup_topic_deadline = @assignment.due_dates.find_by(deadline_type_id: 7)
  end
     @drop_topic_deadline = @assignment.due_dates.find_by(deadline_type_id: 6)
    @student_bids = team_id.nil? ? [] : Bid.where(team_id: team_id)


  def add_date_time_filter
    # Show selected topics only if the assignment's deadline hasn't passed
     "created_at >= '#{time_to_string(params[:start_time])}' AND " +
     unless @assignment.due_dates.find_by(deadline_type_id: 1).nil?
        "created_at <= '#{time_to_string(params[:end_time])}'"
      @show_actions = false if !@assignment.staggered_deadline? and @assignment.due_dates.find_by(deadline_type_id: 1).due_at < Time.now
  end


  def add_version_type_filter (version_type)
      # Find whether the user has signed up for any topics; if so the user won't be able to
    "item_type = '#{version_type}' AND " if version_type && !(version_type.eql? 'Any')
      # sign up again unless the former was a waitlisted topic
      # if team assignment, then team id needs to be passed as parameter else the user's id
      users_team = SignedUpTeam.find_team_users(@assignment.id, session[:user].id)
      @selected_topics = if users_team.empty?
                          nil
                        else
                          # TODO: fix this; cant use 0
                          SignedUpTeam.find_user_signup_topics(@assignment.id, users_team[0].t_id)
                        end
    end
    render 'sign_up_sheet/intelligent_topic_selection' and return if @assignment.is_intelligent
   end
   end
</pre>
</pre>
* The paginate method has been moved to the helper class Pagination_Helper. This new method can be now reused by the different components like UsersController etc. The method receives two parameters, first the list to paginate and second the number of items to be displayed in a page.


<pre>
module PaginationHelper


  def paginate (items, number_of_items_per_page)
* '''Problem 7''': What are the differences between signup_as_instructor and signup_as_instructor_action methods? Investigate if they are needed and improve the method names if both are needed. Provide comments as to what each method does.
    items.page(params[:page]).per_page(number_of_items_per_page)
* '''Solution''': signup_as_instructor  specifies the student and displays a new page called via a get request whereas signup_as_instructor_action is an action called via post request which aims to signup a student.
  end
 


end
* '''Problem 8''': Participants variable in load_add_signup_topics actually means teams that signed up for a topic.
* '''Solution''': Renamed participants variable to 'teams'.
<pre>
    # Though called participants, @participants are actually records in signed_up_teams table, which
    # is a mapping table between teams and topics (waitlisted recored are also counted)
    @participants = SignedUpTeam.find_team_participants(assignment_id, session[:ip])
    @teams = SignedUpTeam.find_team_participants(assignment_id, session[:ip])
</pre>
</pre>


===Code improvements===
* '''Problem 9''': Signup_as_instructor_action has if-else ladder.  
* Introduced a constant VERSIONS_PER_PAGE and assigned the value 25 to it. The pagination algorithm for VersionsController displays at most 25 versions in a page. The existing implementation uses the value 25 straight in the code and there are few problems associated with such an approach.
* '''Solution''': It has been made more elegant using a helper function.
** It is not easy to understand what 25 is unless the programmer takes a close look at the code.
** In case if the value 25 is used at more than one places and in future a new requirement comes to show at most 30 versions in a page, all the values will have to be modified. It is not very DRY.
* The VersionsController was overriding AccessHelper - action_allowed? method to return true in all the cases. This was violating the whole purpose of the method action_allowed?. The purpose of this method is to determine whether the user who is triggering a CRUD operation is allowed to do so. So when the current user invokes a CRUD operation, the action_allowed? method is invoked first and if the method returns true the CRUD operation is triggered or else the user is intimated with a message and gracefully exited. Hence, when the action_allowed? method is overridden to return true always, it results in providing unauthorized access to certain users.


<pre>
<pre>
def action_allowed?
  def signup_student user
     true
    if SignUpSheet.signup_team(params[:assignment_id], user.id, params[:topic_id])
      flash[:success] = "You have successfully signed up the student for the topic!"
      ExpertizaLogger.info LoggerMessage.new(controller_name, '', 'Instructor signed up student for topic: ' + params[:topic_id].to_s)
    else
      flash[:error] = "The student has already signed up for a topic!"
      ExpertizaLogger.info LoggerMessage.new(controller_name, '', 'Instructor is signing up a student who already has a topic')
    end
  end
 
  def signup_as_instructor_action
    user = User.find_by(name: params[:username])
    if user.nil? # validate invalid user
      flash[:error] = "That student does not exist!"
    end
    if !user.nil? and AssignmentParticipant.exists? user_id: user.id, parent_id: params[:assignment_id]
      signup_student(user);
    else
      flash[:error] = "The student is not registered for the assignment!"
      ExpertizaLogger.info LoggerMessage.new(controller_name, '', 'The student is not registered for the assignment: ' << user.id)
    end
     redirect_to controller: 'assignments', action: 'edit', id: params[:assignment_id]
   end
   end
</pre>
</pre>


:With the new implementation the AccessHelper - action_allowed? method has been modified in such a way that unauthorized access is prevented. As per the new algorithm, 'new', 'create', 'edit', 'update' cannot be invoked by any user. These operations can be accessed only by ‘papertrail’ gem. Only an ‘Administrator’ or ‘Super-Administrator’ can call 'destroy_all' method. All the other methods are accessible to ‘Administrator’,  ‘Super-Administrator’, ‘Instructor’, ‘Teaching Assistant’ and ‘Student’.
* '''Problem 10''': Delete_signup and delete_signup_as_instructor have much in common and violates the DRY principle.  
 
* '''Solution''': Refactored them by moving the duplicate code to a helper function.
<pre>
<pre>
   def action_allowed?
   def can_delete_topic? is_instructor, participant, assignment, drop_topic_deadline
     case params[:action]
    submission_error_message = ""
    when 'new', 'create', 'edit', 'update'
    deadline_error_message = ""
    #Modifications can only be done by papertrail
     if is_instructor?
      submission_error_message = "The student has already submitted their work, so you are not allowed to remove them"
      deadline_error_message = "You cannot drop a student after the drop topic deadline!"
    else
      submission_error_message = "You have already submitted your work, so you are not allowed to drop your topic."
      deadline_error_message = "You cannot drop your topic after the drop topic deadline!"
    end
    if !participant.team.submitted_files.empty? or !participant.team.hyperlinks.empty?
      flash[:error] = submission_error_message
      ExpertizaLogger.error LoggerMessage.new(controller_name, session[:user].id, 'Drop failed for already submitted work: ' + params[:topic_id].to_s)
      return false
    elsif !drop_topic_deadline.nil? and Time.now > drop_topic_deadline.due_at
      flash[:error] = deadline_error_message
      ExpertizaLogger.error LoggerMessage.new(controller_name, session[:user].id, 'Drop failed for ended work: ' + params[:topic_id].to_s)
       return false
       return false
    when 'destroy_all'
      ['Super-Administrator',
      'Administrator'].include? current_role_name
    else
      #Allow all others
      ['Super-Administrator',
      'Administrator',
      'Instructor',
      'Teaching Assistant',
      'Student'].include? current_role_name
     end
     end
    return true
   end
   end
</pre>


===Automated Testing using RSPEC===
  # this function is used to delete a previous signup
The current version of expertiza did not have any test for VersionsController. Using the test driven development(TDD) approach, we have added an exhaustive set of RSPEC tests for VersionsController, to test all the modifications we have done to the code of the controller class. The tests use double and stub features of rspec-rails gem, to fake the log in by different users - Administrator, Instructor, Student etc. The tests can be executed "rpec spec" command as shown below.
  def delete_signup
<pre>
    participant = AssignmentParticipant.find(params[:id])
user-expertiza $rspec spec
    assignment = participant.assignment
.
    drop_topic_deadline = assignment.due_dates.find_by(deadline_type_id: 6)
.
    # A student who has already submitted work should not be allowed to drop his/her topic!
.
    # (A student/team has submitted if participant directory_num is non-null or submitted_hyperlinks is non-null.)
Finished in 5.39 seconds (files took 25.33 seconds to load)
    # If there is no drop topic deadline, student can drop topic at any time (if all the submissions are deleted)
66 examples, 0 failures
    # If there is a drop topic deadline, student cannot drop topic after this deadline.
    if can_delete_topic?(false, participant, assignment, drop_topic_deadline)
      delete_signup_for_topic(assignment.id, params[:topic_id], session[:user].id)
      flash[:success] = "You have successfully dropped your topic!"
      ExpertizaLogger.info LoggerMessage.new(controller_name, session[:user].id, 'Student has dropped the topic: ' + params[:topic_id].to_s)
    end
    redirect_to action: 'list', id: params[:id]
  end


Randomized with seed 19254
  def delete_signup_as_instructor
.
    # find participant using assignment using team and topic ids
.
    team = Team.find(params[:id])
    assignment = Assignment.find(team.parent_id)
    user = TeamsUser.find_by(team_id: team.id).user
    participant = AssignmentParticipant.find_by(user_id: user.id, parent_id: assignment.id)
    drop_topic_deadline = assignment.due_dates.find_by(deadline_type_id: 6)
    if can_delete_topic?(true, participant, assignment, drop_topic_deadline)
      delete_signup_for_topic(assignment.id, params[:topic_id], participant.user_id)
      flash[:success] = "You have successfully dropped the student from the topic!"
      ExpertizaLogger.error LoggerMessage.new(controller_name, session[:user].id, 'Student has been dropped from the topic: ' + params[:topic_id].to_s)
    end
    redirect_to controller: 'assignments', action: 'edit', id: assignment.id
  end
</pre>
</pre>


===Testing from UI===
===Testing===
Following are a few testcases with respectto our code changes that can be tried from UI:
1. To go to versions index page, type in the following url after logging in:
  http://152.46.16.81:3000/versions
 
2. After logging in as student/instructor or admin : Try accessing the  new, create, edit, update actions. These actions are not allowed to any of the users.
  http://152.46.16.81:3000/versions/new
  This calls the new action. In the current production version of expertiza, it is unhandled and application gives a default 404 page.
 
3. Another feature that can be tested from UI is Pagination. Try searching for a user's versions and see if the results are paginated or not. Search here:
  http://152.46.16.81:3000/versions/search


4. Visit the same URL as step 3, you should see only the students under that instructor in the users dropdown.
As the project involved only refactoring variables and method names, only build tests and already existing unit tests were performed.


===References===
===References===


#[https://github.com/expertiza/expertiza Expertiza on GitHub]
#https://github.com/expertiza/expertiza
#[https://github.com/WintersLt/expertiza GitHub Project Repository Fork]
#http://expertiza.ncsu.edu/ The live Expertiza website
#[http://expertiza.ncsu.edu/ The live Expertiza website]
#[http://bit.ly/myexpertiza  Demo link]
#[http://wikis.lib.ncsu.edu/index.php/Expertiza Expertiza project documentation wiki]
#[https://relishapp.com/rspec Rspec Documentation]
#Clean Code: A handbook of agile software craftsmanship. Author: Robert C Martin

Latest revision as of 01:05, 28 March 2019

E1908. Refactoring the Sign-up sheet Controller

This page provides a description of the Expertiza based OSS project.



About Expertiza

[1] is an open source project dependent on on Rails structure. Expertiza enables the teacher to make new assignments and alter new or existing assignments. It additionally enables the educator to make a rundown of subjects the students can agree to accept. Students can shape groups in Expertiza to chip away at different undertakings and projects. Students can likewise peer audit other students' entries. Expertiza underpins accommodation crosswise over different record types, including the URLs and wiki pages.


Problem Statement

The following tasks were accomplished in this project:

  • Improved the clarity of code by improving the variable and parameter names.
  • Followed naming conventions throughout and renamed methods with inconsistent names including the calling methods.
  • Rectified several unwanted if-else conditions in methods and optimized the code.
  • Refactored all instance variables and removed unnecessarily defined variables.
  • Removed certain unwanted flash messages that occur for some user actions.
  • Included comments for functionalities throughout for better understanding.

About Sign-up sheet Controller

Sign-up sheet controller contains all functions related to management of the signup sheet for an assignment function to add new topics to an assignment, edit properties of a particular topic, delete a topic, etc are included here.


Issues and Fixes
  • Problem 1: Create method has an if-else condition determining if create or update should be called. Create method should not be responsible for calling update. Identify why the if-else condition exists. The if-else condition exists because the current implementation calls update if a signup sheet with the same name already exists.
  • Solution: Rectified this method by removing the call to update and flashing an error instead.

 if topic.nil?
      setup_new_topic
    else
      # update_existing_topic topic
      # Create must not be used for calling update. So replaced it with an error message
      flash[:error] = "The topic already exists."
    end
  end

  • Problem 2: Update method has a plethora of instance variables defined before updating. These are not necessary (For e.g., look at update method of bookmarks_controller).
  • Solution: Refactored the variables not needed out.

      update_max_choosers @topic
      # @topic.category = params[:topic][:category]
      # @topic.topic_name = params[:topic][:topic_name]
      # @topic.micropayment = params[:topic][:micropayment]
      # @topic.description = params[:topic][:description]
      # @topic.link = params[:topic][:link]
      # @topic.save
      # Replaced all the above unnecessary variables and save with a single update call for all the parameters
      @topic.update_attributes(topic_identifier: params[:topic][:topic_identifier], category: params[:topic][:category], topic_name: params[:topic][:topic_name], micropayment: params[:topic][:micropayment], description: params[:topic][:description], link: params[:topic][:link])


  • Problem 3: Destroy has a misleading else flash message.
  • Solution: Refactored the mislleading flash messages not needed out.

   @topic.destroy
      undo_link("The topic: \"#{@topic.topic_name}\" has been successfully deleted. ")
    else
      # Replaced this flash[:error] = "The topic could not be deleted." with
      flash[:error] = "This topic could not be found." # error message mage more specific
    end
    # changing the redirection url to topics tab in edit assignment view.
    redirect_to edit_assignment_path(params[:assignment_id]) + "#tabs-5"



  • Problem 4: Add_signup_topics_staggered does not do anything.
  • Solution: Renamed participants variable to 'teams'.
 # add_signup_topics_staggered calls add_signup_topics and does nothing else. So removed the following function.
 def add_signup_topics_staggered
    add_signup_topics 
  end
  • Problem 5: Several method names are renamed to be more intuitive.
  • Solution: load_add_signup_topics is renamed to get_assignment_data and ad_info is renamed to get_ad.
  # Contains links that let an admin or Instructor edit, delete, view enrolled/waitlisted members for each topic
  # Also contains links to delete topics and modify the deadlines for individual topics. Staggered means that different topics can have different deadlines.
  # def load_add_signup_topics(assignment_id)  previously
  def get_assignment_data(assignment_id)
    @id = assignment_id
    @sign_up_topics = SignUpTopic.where('assignment_id = ?', assignment_id)
    @slots_filled = SignUpTopic.find_slots_filled(assignment_id)


  • Problem 6: The list method is too long and is sparsely commented.
  • Solution: Added comments.

  # function to list all topics and bids to a participant
  def list
    @participant = AssignmentParticipant.find(params[:id].to_i)
    @assignment = @participant.assignment
    @slots_filled = SignUpTopic.find_slots_filled(@assignment.id)
    @slots_waitlisted = SignUpTopic.find_slots_waitlisted(@assignment.id)
    @show_actions = true
    @priority = 0
    @sign_up_topics = SignUpTopic.where(assignment_id: @assignment.id, private_to: nil)
    @max_team_size = @assignment.max_team_size
    team_id = @participant.team.try(:id)

    # If the assignment supports bidding, add all the bids of an 
    # individual or team to the list of signed topics
    if @assignment.is_intelligent
      @bids = team_id.nil? ? [] : Bid.where(team_id: team_id).order(:priority)
      signed_up_topics = []
      @bids.each do |bid|
        sign_up_topic = SignUpTopic.find_by(id: bid.topic_id)
        signed_up_topics << sign_up_topic if sign_up_topic
      end
      signed_up_topics &= @sign_up_topics
      @sign_up_topics -= signed_up_topics
      @bids = signed_up_topics
    end

    @num_of_topics = @sign_up_topics.size
    @signup_topic_deadline = @assignment.due_dates.find_by(deadline_type_id: 7)
    @drop_topic_deadline = @assignment.due_dates.find_by(deadline_type_id: 6)
    @student_bids = team_id.nil? ? [] : Bid.where(team_id: team_id)

    # Show selected topics only if the assignment's deadline hasn't passed
    unless @assignment.due_dates.find_by(deadline_type_id: 1).nil?
      @show_actions = false if !@assignment.staggered_deadline? and @assignment.due_dates.find_by(deadline_type_id: 1).due_at < Time.now

      # Find whether the user has signed up for any topics; if so the user won't be able to
      # sign up again unless the former was a waitlisted topic
      # if team assignment, then team id needs to be passed as parameter else the user's id
      users_team = SignedUpTeam.find_team_users(@assignment.id, session[:user].id)
      @selected_topics = if users_team.empty?
                           nil
                         else
                           # TODO: fix this; cant use 0
                           SignedUpTeam.find_user_signup_topics(@assignment.id, users_team[0].t_id)
                         end
    end
    render 'sign_up_sheet/intelligent_topic_selection' and return if @assignment.is_intelligent
  end


  • Problem 7: What are the differences between signup_as_instructor and signup_as_instructor_action methods? Investigate if they are needed and improve the method names if both are needed. Provide comments as to what each method does.
  • Solution: signup_as_instructor specifies the student and displays a new page called via a get request whereas signup_as_instructor_action is an action called via post request which aims to signup a student.


  • Problem 8: Participants variable in load_add_signup_topics actually means teams that signed up for a topic.
  • Solution: Renamed participants variable to 'teams'.
    # Though called participants, @participants are actually records in signed_up_teams table, which
    # is a mapping table between teams and topics (waitlisted recored are also counted)
    @participants = SignedUpTeam.find_team_participants(assignment_id, session[:ip])
    @teams = SignedUpTeam.find_team_participants(assignment_id, session[:ip])
  • Problem 9: Signup_as_instructor_action has if-else ladder.
  • Solution: It has been made more elegant using a helper function.
  def signup_student user
    if SignUpSheet.signup_team(params[:assignment_id], user.id, params[:topic_id])
      flash[:success] = "You have successfully signed up the student for the topic!"
      ExpertizaLogger.info LoggerMessage.new(controller_name, '', 'Instructor signed up student for topic: ' + params[:topic_id].to_s)
    else
      flash[:error] = "The student has already signed up for a topic!"
      ExpertizaLogger.info LoggerMessage.new(controller_name, '', 'Instructor is signing up a student who already has a topic')
    end
  end

  def signup_as_instructor_action
    user = User.find_by(name: params[:username])
    if user.nil? # validate invalid user
      flash[:error] = "That student does not exist!"
    end
    if !user.nil? and AssignmentParticipant.exists? user_id: user.id, parent_id: params[:assignment_id]
      signup_student(user);
    else
      flash[:error] = "The student is not registered for the assignment!"
      ExpertizaLogger.info LoggerMessage.new(controller_name, '', 'The student is not registered for the assignment: ' << user.id)
    end
    redirect_to controller: 'assignments', action: 'edit', id: params[:assignment_id]
  end
  • Problem 10: Delete_signup and delete_signup_as_instructor have much in common and violates the DRY principle.
  • Solution: Refactored them by moving the duplicate code to a helper function.
  def can_delete_topic? is_instructor, participant, assignment, drop_topic_deadline
    submission_error_message = ""
    deadline_error_message = ""
    if is_instructor?
      submission_error_message = "The student has already submitted their work, so you are not allowed to remove them"
      deadline_error_message = "You cannot drop a student after the drop topic deadline!"
    else
      submission_error_message = "You have already submitted your work, so you are not allowed to drop your topic."
      deadline_error_message = "You cannot drop your topic after the drop topic deadline!"
    end
    if !participant.team.submitted_files.empty? or !participant.team.hyperlinks.empty?
      flash[:error] = submission_error_message
      ExpertizaLogger.error LoggerMessage.new(controller_name, session[:user].id, 'Drop failed for already submitted work: ' + params[:topic_id].to_s)
      return false
    elsif !drop_topic_deadline.nil? and Time.now > drop_topic_deadline.due_at
      flash[:error] = deadline_error_message
      ExpertizaLogger.error LoggerMessage.new(controller_name, session[:user].id, 'Drop failed for ended work: ' + params[:topic_id].to_s)
      return false
    end
    return true
  end

  # this function is used to delete a previous signup
  def delete_signup
    participant = AssignmentParticipant.find(params[:id])
    assignment = participant.assignment
    drop_topic_deadline = assignment.due_dates.find_by(deadline_type_id: 6)
    # A student who has already submitted work should not be allowed to drop his/her topic!
    # (A student/team has submitted if participant directory_num is non-null or submitted_hyperlinks is non-null.)
    # If there is no drop topic deadline, student can drop topic at any time (if all the submissions are deleted)
    # If there is a drop topic deadline, student cannot drop topic after this deadline.
    if can_delete_topic?(false, participant, assignment, drop_topic_deadline)
      delete_signup_for_topic(assignment.id, params[:topic_id], session[:user].id)
      flash[:success] = "You have successfully dropped your topic!"
      ExpertizaLogger.info LoggerMessage.new(controller_name, session[:user].id, 'Student has dropped the topic: ' + params[:topic_id].to_s)
    end
    redirect_to action: 'list', id: params[:id]
  end

  def delete_signup_as_instructor
    # find participant using assignment using team and topic ids
    team = Team.find(params[:id])
    assignment = Assignment.find(team.parent_id)
    user = TeamsUser.find_by(team_id: team.id).user
    participant = AssignmentParticipant.find_by(user_id: user.id, parent_id: assignment.id)
    drop_topic_deadline = assignment.due_dates.find_by(deadline_type_id: 6)
    if can_delete_topic?(true, participant, assignment, drop_topic_deadline)
      delete_signup_for_topic(assignment.id, params[:topic_id], participant.user_id)
      flash[:success] = "You have successfully dropped the student from the topic!"
      ExpertizaLogger.error LoggerMessage.new(controller_name, session[:user].id, 'Student has been dropped from the topic: ' + params[:topic_id].to_s)
    end
    redirect_to controller: 'assignments', action: 'edit', id: assignment.id
  end

Testing

As the project involved only refactoring variables and method names, only build tests and already existing unit tests were performed.

References

  1. https://github.com/expertiza/expertiza
  2. http://expertiza.ncsu.edu/ The live Expertiza website