Coding session

Good Things


  • Controller logic to Models
  • Models logic to Modules
  • -
  • View logic to Decorators
  • View logic to Helpers

Why Good ?


  • Skinny Controllers -> Readable
  • Models -> Reusable
  • Modules -> Single Responsability
  • Decorators -> Readable

Bad Things


  • Naming
  • Namespacing
  • Big Methods

Naming


  • What 'Paginate' should do ?
  • Actually, 'Paginate' is a module that define behavior for pagination
  • Possible good naming could be 'Paginable'  

Naming


  • What 'pool_url' should do ?
  • Actually, its display not only the url, but the full link tag
  • Possible good naming could be just 'pool', as its belongs in a decorator

Facing Problems


  • What to refactor
  • What priority 
  • Make a "junk" module OR severals skinny modules
  • Refactoring too fast

What to refactor and priority


  1. Controller logic into Models
  2. View logic into Decorators
  3. Models logic into Modules
  4. View logic into Helpers
  5. Helpers & Modules into namespaced Class
 

The END ?

AREL + Active Record


  • AREL = Relational Algebra
  • Active Record = ORM
  • -
  • AREL means Active Relation
  • ORM means Object-Relational Mapping

How the logic works


  • AREL construct the query
  • users = User.where(admin: true)
  • This is not a collection, it's an ActiveRelation object
  • ordered_users = user.order("name ASC")
  • -
  • ActiveRecord perform the query an translate it into ruby
  • users = users.all.to_a
  • This is a collection of User
  • Method 'to_a' force the query to be executed and wrapped in a collection

Coding !


  • Make an simple AREL/ActiveRecord yourself !
  • Complete the ArticlesController#coding_arel method
  • http://192.168.10.10:3000/articles/coding_arel
  • -
  • Hint : Keep it simple (to code, and to use)
  • Hint : Use Model.find_by_sql("query") to perform SQL
  • Hint : Use ActiveSupport::Inflector#tableize
  • Hint : Use ActiveRelation#to_sql to see SQL syntax
  • -
  • When you'r done, refactor (step by step)

Coding session - review

By Thomas Petrachi

Coding session - review

  • 1,232