Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Refactoring Views in Rails

Refactoring Views in Rails

Presentation to the Las Vegas Ruby Group, 6/5/13

Brian V. Hughes

June 05, 2013
Tweet

More Decks by Brian V. Hughes

Other Decks in Technology

Transcript

  1. MVC in Rails C M V It’s Anti-SRP! • Receive

    HTTP Requests • Process Parameters • Delegate Business Logic to Models • Delegate UI Rendering to Views • Persist the Data • Validate Attributes • Process Queries • Perform Business Logic • • Render HTML/CSS/JS • Interpolate Ruby code • Present Model data • Manage App State Thursday, June 6, 13
  2. MVC in Rails C M V • Receive HTTP Requests

    • Process Parameters • Delegate Business Logic to Models • Delegate UI Rendering to Views • Persist the Data • Validate Attributes • Process Queries • Perform Business Logic • • Render HTML/CSS/JS • Interpolate Ruby code • Present Model data • Manage App State Skinny Controllers, Fat Models Thursday, June 6, 13
  3. MVC in Rails C V S • Business Logic •

    Process Forms • Complex Queries Service Classes can help make our models thin. M Thursday, June 6, 13
  4. MVC in Rails C M V S • Business Logic

    • Process Forms • Complex Queries Service Classes can help make our models thin. Thursday, June 6, 13
  5. MVC in Rails V C M S How do we

    deal with Views, when they get fat? Thursday, June 6, 13
  6. Dealing with Fat Views The Rails Way: Helpers Methods in

    modules. Not regular classes Can have name collisions Procedural in nature Difficult to test We Don’t Need that kind of Help V Thursday, June 6, 13
  7. Objects, not Helpers Standard classes, with standard methods Knows the

    state of our Model objects Provides presentation-specific data, when needed Knows how to render sub-templates Can be tested, just like our other classes V Thursday, June 6, 13
  8. I’ll bet he’s talking about Design Patterns! Decorator Pattern One

    of the original GoF patterns Exhibit Pattern Objects on Rails, Avdi Grimm Presenter Pattern Introduced by Jay Fields, 2007 V Thursday, June 6, 13
  9. How do I use these in my Rails app? Roll

    your own Decorator Using Ruby stdlib’s SimpleDelegator Display Case – Exhibits github.com/objects-on-rails/display-case Draper github.com/drapergem/draper V Thursday, June 6, 13
  10. What is Draper? The most popular gem for View refactoring

    A bit confused about design patterns Almost a pure implementation of Presenter Calls itself a View-Model Stores classes in /app/decorators V Thursday, June 6, 13
  11. When should we refactor our Views? When we find Code

    Smells! Use of conditionals: if, else, unless, case Performing an ActiveRecord query Processing Arrays/Hashes: each, map Formatting model data for presentation Improper use of partial templates Instantiating local variables V Thursday, June 6, 13