CSC/ECE 517 Fall 2024 - E2450. Refactor assignments controller.rb

From Expertiza_Wiki
Jump to navigation Jump to search

About Controller

The `AssignmentsController` handles actions related to managing assignments.Key functionalities include initializing a new assignment in the `new` action and creating assignments through the `create` action, with validations to prevent duplicate names and directory paths. If creation succeeds, it redirects appropriately; otherwise, it renders the form with errors. This controller ensures smooth assignment management by enforcing proper validations and access control throughout the process.

Functionality of assignments_controller

The `AssignmentsController` handles the management of assignments by providing actions for creating and initializing them while ensuring access control. It uses `before_action` callbacks to enforce authorization, ensuring only permitted users can interact with assignment-related features. The `new` action initializes a blank assignment object for form rendering, facilitating the creation of new assignments. Additionally, the `create` action is responsible for processing form submissions, validating input, and saving the assignment if it meets the criteria. This controller ensures that all assignment operations are secure, properly initialized, and follow the required business logic.

Problem Statement

The `assignments_controller` presents difficulties due to its large size, intricate structure, and absence of comments, making it challenging for developers to grasp its functionality. To address these issues, a thorough refactor is advised, breaking down lengthy methods into smaller, more manageable sections. This strategy would modularize complex logic, assigning specific tasks to individual parts within the controller’s responsibilities. Furthermore, the refactor should aim to remove redundant code by consolidating repetitive sections into reusable functions or utilities, enhancing code quality and reducing the risk of errors. By restructuring the controller and improving its documentation, developers can better understand its operations, making maintenance, debugging, and future updates more straightforward.

Tasks

1. Refactor create method

2. Refactor edit method

3. Refactor update method

4. Refactor delete method: New models for subclasses will be implemented to streamline organization and simplify management.

5. Reposition methods

6. Enhance Comments

7. Expand Test Coverage

Phase 1

  1. Clarify and Refactor exist_assignment variable.
  2. Clarify aq Parameter Naming in list_unassigned_rubrics & remove_existing_questionnaire.
  3. Fixing the Github required checks.
  4. Refactor Variable Naming for Clarity.
  5. Review path Method Location.
  6. Refactor Authorization Checks.
  7. Simplify Array Usage in Create Method.
  8. Refactor Method Names with 'Check'.
  9. Refactor query_participants_and_alert Method.

Phase 2

Current Status

We have successfully completed the following refactoring and functionality improvements:
 1. Refactor query_participants_and_alert Method
  Refactored query_participants_and_alert by splitting it into missing_participants? and alert_missing_participants for improved readability and       maintainability. 
  The new missing_participants? method checks if participants are blank, while alert_missing_participants generates a flash error message with a link to add    missing participants.
2. Clarify and Refactor Variable Naming for Clarity
 a. Renamed find_existing_assignment to assignment_by_name for consistency with Ruby conventions.
 b. Renamed exist_assignment to assignment_created to clearly indicate it tracks assignment creation status.
 c. Renamed the aq parameter to assignment_questionnaire for clarity in assignment questionnaire iterations.
3. Refactor Authorization Checks
 Centralized privilege-checking logic by replacing direct role checks with helper methods current_user_has_instructor_privileges? and   current_user_has_ta_privileges?, enhancing maintainability and aligning with DRY principles.
4. Simplify Array Usage in create Method
 Simplified the check method by renaming it to validate and removing unnecessary arrays (ques_array and due_array). Direct data structure traversal is now   used, reducing complexity and enhancing clarity.

These changes have been implemented and tested to ensure they meet the requirements for clarity, functionality, and performance.

Issues and Plan of Action For Phase 2

1. Assess Method Placement for Assignment Name Check

Current Issue: The method that checks if an assignment name is already in use currently resides in the controller. This placement may violate the separation of concerns principle, as it could be more fitting for a model or service object to handle this validation.
Plan: Analyze the current functionality of the assignment name check and determine if it involves complex logic that could be encapsulated within a service object or model. If it's a simple validation, move it to the model; for more complex operations, implement a service object to streamline the controller and enhance reusability across the application.

2. Simplify path_warning_and_answer_tag Method

Current Issue: The path_warning_and_answer_tag method has a verbose name and may be performing multiple tasks, making it hard to read and maintain.
Plan: Rename path_warning_and_answer_tag to a clear, action-oriented name and refactor the method by breaking it into smaller, single-purpose methods. Each new method should encapsulate one logical part of the process, improving readability, modularity, and simplifying future maintenance.

3. Evaluate Bookmarking Functionality

Current Issue: Bookmarking assignments and managing badges may not be logically consistent within the current context, creating ambiguity about where and how these features should be implemented.
Plan: Review the current use cases for bookmarking and badge handling to establish if these features align with the current controller or model. If they serve a broader purpose or require more context-specific handling, consider relocating them to a dedicated module or service. Create a detailed design proposal for implementing and managing these features effectively.

4. Move Assignment Management Methods to Model

Current Issue: The methods remove_assignment_from_course and place_assignment_in_course are currently in the controller, but they deal with assignment management, which may belong more appropriately in the model.
Plan: Move remove_assignment_from_course and place_assignment_in_course to the assignment model to adhere to the principle of separating concerns. Adjust the controller to call these model methods, keeping the controller focused on handling HTTP requests while the model manages data-related logic.

5. Reassess Delayed Mailer Methods

Current Issue: The delayed_mailer and delete_delayed_mailer methods reside in the controller but may not need to be there, especially if they are used for background email processes that can be managed elsewhere.
Plan: Evaluate the purpose and functionality of these delayed mailer methods. If they are intended to manage background processes, consider relocating them to a service object or a background job manager to enhance modularity. Ensure the new placement supports asynchronous processing while reducing the controller’s load.

6. Addressing Code Climate Issues

Current Issue: Code climate flags include high complexity and excessive line count
Plan: Refactor by:
 Splitting complex logic into smaller helper methods
 Reducing nested conditionals and loops
 Improving readability through concise naming and streamlined code
 These adjustments will enhance maintainability and meet Code Climate’s metrics for complexity and line limits.

7. Remove HTML Markup Code From the Controller

Current Issue: There is HTML markup code present in the controller, especially in Flash messages
Plan: Evaluate the current controller to identify HTML markup in Flash messages and remove it, adhering to MVC principles. Refactor the controller to pass raw, clean data (without HTML) to the view. In the view, update Flash message rendering to handle HTML formatting using Rails helpers like raw or sanitize for security. Test thoroughly to ensure functionality and proper display across browsers. Finally, update documentation and request a code review before deploying the changes.

Test Cases

All of the required checks for tests are passing. This is shown in the image below. The previously written test cases were not changed, just modified the cases to incorporate our refactoring.

Implementation

Refactor query_participants_and_alert Method

What

The method `query_participants_and_alert` was refactored to improve readability and maintainability by splitting it into two distinct methods.

Why

The method was initially complex, with inline logic that reduced readability.

How

The inline check for participants was moved to a new method `missing_participants?` in `assignment.rb`, which now simply checks if participants are blank. The alerting functionality was moved to a new `alert_missing_participants` method. This method generates a flash error message and adds a link to help the user add participants if they are missing.

Clarify and Refactor Variable Naming for Clarity

a. `find_existing_assignment` Renamed to `assignment_by_name`

What

Renamed `find_existing_assignment` to `assignment_by_name`.

Why

The original name was verbose and inconsistent with Ruby conventions.

How

Renamed `find_existing_assignment` to `assignment_by_name` to more accurately describe the purpose of the variable.

b. `exist_assignment` Renamed to `assignment_created`

What

Renamed `exist_assignment` to `assignment_created`.

Why

The original name was ambiguous and could lead to confusion.

How

Renamed `exist_assignment` to `assignment_created` to clearly indicate that the variable tracks the creation status of an assignment.

c. `aq` Parameter Renamed to `assignment_questionnaire`

What

Renamed `aq` parameter to `assignment_questionnaire`.

Why

The `aq` parameter used in loops lacked descriptive power, making it harder for developers to interpret its purpose.

How

Renamed `aq` to `assignment_questionnaire` to better indicate the parameter’s context in assignment questionnaire iterations.

Refactor Authorization Checks

What

Centralized privilege-checking logic by using helper methods from the `AuthorizationHelper` module.

Why

Direct role checks created redundant code, as privilege-checking logic was scattered and duplicated.

How

Replaced direct role checks with calls to `current_user_has_instructor_privileges?` and `current_user_has_ta_privileges?`, enhancing maintainability and aligning with DRY principles.

Simplify Array Usage in Create Method

What

Reduced complexity by removing unnecessary arrays in the `check` method.

Why

The `check` method was generic and not expressive enough for its validation purposes, and `ques_array` and `due_array` added unnecessary complexity.

How

Renamed `check` to `validate`, making the method’s purpose clearer and aligning with common naming conventions. Removed `ques_array` and `due_array`, opting to directly traverse data structures where possible.

Implementation Phase 2

Assess Method Placement for Assignment Name Check

What

Analyze and potentially relocate the method that checks whether an assignment name is already in use.

Why

The current placement in the controller violates the separation of concerns principle, potentially complicating future scalability and maintenance.

How

- Review the method's logic to determine its complexity. - For simple validation, move the method to the model. - For more complex logic, implement a dedicated service object to handle this validation. - Update the controller to call the refactored method from its new location.

Simplify path_warning_and_answer_tag Method

What

Refactor the `path_warning_and_answer_tag` method to simplify its logic and improve maintainability.

Why

The method's verbose name and multipurpose nature make it difficult to understand and maintain, leading to potential errors and technical debt.

How

- Rename the method to a concise, action-oriented name that clearly indicates its purpose. - Break down the method into smaller, single-purpose helper methods. - Ensure each new method encapsulates a distinct logical step, improving modularity and readability.

Evaluate Bookmarking Functionality

What

Review the logic and placement of bookmarking assignments and managing badges.

Why

Current implementation may lack logical consistency, creating ambiguity in functionality and future scalability challenges.

How

- Analyze the use cases for bookmarking and badge management. - If they serve broader purposes or overlap with other features, create a dedicated module or service object. - Propose and implement a design plan that ensures these features are logically and contextually consistent across the application.

Move Assignment Management Methods to Model

What

Relocate the methods `remove_assignment_from_course` and `place_assignment_in_course` to the assignment model.

Why

These methods pertain to assignment data and logic, which align more closely with the model layer than the controller.

How

- Transfer the methods to the assignment model. - Refactor the controller to call the model methods instead, ensuring a clean separation of concerns. - Test the updated methods for functionality and performance.

Reassess Delayed Mailer Methods

What

Relocate `delayed_mailer` and `delete_delayed_mailer` methods to an appropriate service or background job manager.

Why

Background email processes do not belong in the controller, and relocating them will enhance modularity and support asynchronous processing.

How

- Evaluate the functionality of these methods and the most suitable framework (e.g., ActiveJob, Sidekiq). - Create a service object or background job manager for email-related processes. - Refactor the controller to invoke the relocated methods, ensuring functionality remains intact.

Addressing Code Climate Issues


What

Refactor code to address issues flagged by Code Climate, including high complexity and excessive line counts.

Why

Simplifying the code will improve readability, maintainability, and compliance with best practices.

How

- Break down complex logic into smaller helper methods. - Minimize nested conditionals and loops. - Refactor variable and method names for conciseness and clarity. - Regularly test during refactoring to ensure correctness and alignment with metrics.

Remove HTML Markup Code From the Controller

What

Eliminate HTML markup in Flash messages and other parts of the controller.

Why

Including HTML in the controller violates MVC principles and can introduce maintainability and security issues.

How

- Identify instances of HTML markup in the controller, focusing on Flash messages. - Refactor the controller to pass raw data to the views. - Use Rails helpers like `raw` or `sanitize` in views for rendering HTML securely. - Thoroughly test the changes for compatibility and correctness. - Update documentation to reflect the new approach, and request a code review prior to deployment.


Test Plan

1. Verified that all refactored methods, including those relocated to models or service objects, worked correctly on the UI, maintaining expected functionality, such as assignment name validation and bookmarking features.

2. Ensured all unit tests and integration tests were updated and passed successfully, with results validated through GitHub Actions for every refactored module.

3. Confirmed the UI reflected accurate behavior after refactoring, including displaying warnings, answer tags, and Flash messages without regressions or errors.

4. Validated that complex processes, such as delayed mailers, badges and assignment management, were functioning seamlessly post-refactoring, with logs and user flows checked for correctness.


5. Addressed and resolved Code Climate issues, ensuring improved code readability, reduced complexity, and compliance with maintainability metrics, supported by thorough testing and attached screenshots of successful outcomes.


Team

Mentor

  • Ameya Vaichalkar

Members

  • Avleen Mehal
  • Daksh Pratap Singh
  • Abhinav Sharma

References

  1. Expertiza