David Bryant Copeland - Sustainable Web Development with Ruby on Rails
Current position: Chapter 1
My Summary
- Work with Rails not against it where possible
- Use default resource routes where possible - devs will know where the code is even years from now
Chapter 1 - Why This Book Exists
- What is sustainable development?
- Easily support new requirements
- Can be worked on by many different people
- Agile often pushes us to YAGNI (You ain't gonna need it)
- Of course there is always the danger of overengineering
- YAGNI gets software shipped but it does not actively drive development of supporting architecture for sustainability
like
- Log statements
- Design Systems for easy UI construction
- Assumptions of the advice in this book
- The Software has a clear purpose (i.e. it's not still experimenting and trying to find its market)
- The Software needs to exist for years
- The Software will evolve
- The Team will change
- You value sustainability, consistency and quality
- Quality needs to be part of the day to day process - the day to pay down technical debt usually doesn't come unless there's a catastrophic failure
- Opportunity Cost vs Carrying Cost
- Carrying cost: Cost that is paid everytime when maintaining/using something
- Each line of code is a carrying cost
- Each feature has a carrying cost
- Each thing we need to remember is a carrying cost
- Opportunity cost: One time investment to produce something to reduce carrying cost
- By making such a decision you cut off your potential future solution space
- Carrying cost: Cost that is paid everytime when maintaining/using something
- To develop a software sustainably you need to keep your carrying cost down
- Sometimes you need to strategically incur opportunity cost to keep your carrying cost in check
- Rails' is designed in a way that keeps your carrying cost low for many common webapp patterns
Chapter 2 - The Rails Application Architecture
- Parts of a Rails App
- Boundaries: Accept Input from somewhere and return output
- Views: HTML, ERB, CSS etc
- Models
- Everything Else
- Tests, Dependencies, Seeds,
bin/setup
- Tests, Dependencies, Seeds,
- Pros and Cons of the Architecture
- Pro: No big upfront decisions needed to get started
- Pro: Lots of conventions for naming etc - it's easy to maintain the architecture
- Con: It's designed to build a DB backed webapp
- Con: Rails gives no guidance on where business logic should go
Chapter 4 - Start Your App Off Right
- Things assumed about the app
- Other developers will work on it and need to
- set it up
- run tests locally
- run the app
- It will have security vulnerabilties
- It will be deployed to production via a CI pipeline
- It will need operational observability
- Other developers will work on it and need to
- Setting up a Developer Workflow by providing a set of scripts
bin/setup- Set up the app after cloning itbin/run- Run the app locally using environment variables via thedotenvgembin/ci- Run tests and other checks likebrakemanandbundle audit
- Manage runtime env consistently via UNIX Environment variables
- Having all of
database.yml,credentials.yml.encandmaster.keyto store environment is confusing - Better delete all of them
- Use
dotenvfor test/development- can also be safely checked in
- Gitignore
.env- if checked in its purpose is very unclear - Gitignore
.env.*.local
- Don't use
dotenvin production
- Having all of
- Write comments, about why libraries are there
bin/setup(written in Ruby)- Reset local database regularly to remove old test data / production data for troubleshooting
- Add comments to each setup step explaining why
- Use some nice helpers like:
system!abort when command failsloglog with a prefix to know it was written by the script and not an executed command
bin/ci- Run tests
- Run Brakeman & output to brakeman.html
- Run Bundle audit
- Use
logragefor logs- Turns off coloring (though that can be done with the
colorize_loggingoption too) - Puts request logs on a simple 1 line format
method=GET path=/jobs/833552.json format=json controller=JobsController action=show status=200 duration=58.33 view=40.43 db=15.26- Requires you to properly set the logger formatter to get timestamps
- Turns off coloring (though that can be done with the
Chapter 5 - Business Logic (Does Not Go In Active Records)
- Rails is optimized for CRUD
- Essential/necessary complexity: Everything on top of normal CRUD that makes your App Special
- Conditional updates, data formatting, calling 3rd party services
- Accidental/unnecessary complexity: Architectural decisions that add complexity that didn't have to be there
- For example manage users in another app and manage via API calls rather than storing it the own database
- Business logic is made up of both types of complexity
- Business logic changes often = High churn
- High complexity + High churn = A paradise for bugs
- Fan out: How many other classes you call
- Fan in: How often other modules/classes call you
- Classes with high fan in are most likely to cause system-wide bugs
- To reduce system-wide bugs: Minimize the complexity and minimize the churn of high fan-in classes
- ActiveRecord classes are the most used classes in Rails apps
- Business logic has high complexity & high church
- Therefore: Keep business logic out of ActiveRecord classes
- Add a service layer between your Controllers and ActiveRecords
- Logic on Active Records
Product#search,Product#rate,Product#purchase,Product#purchase_by_tax- Every controller uses
Product
- With a Service Layer in between
- Several service classes:
ProductPurchaser#purchase,ProductPurchaser#purchase_by_taxProductRater#rateProductSearch#search
- Each of those new classes is only used by 1 or two controllers
- All complex business logic is contained in those classes
- Several service classes:
- Logic on Active Records
Chapter 6 - Routes and URLs
- Stick with Rails conventions for canonical routes, use
resourceswhere possible- Developers will immediately know how the app is organized
- You won't have to make architectural decisions
- Don't create unused routes (use
only:) - Add custom routes as a separate section below normal routes as redirects to canonical urls
- Add a comment explaining why it's needed
- You can also use a normal
getetc helper if you don't want any redirects
- Prefer creating new resources rather than custom actions
- Rails works best when focused on resources + standard actions
resource :product_ratings, only: %i[create]rather thanresource :products, only: %i[...., rate]
- Prefer separate resources over nested resources.....
- Rails Guid recommends to only nest resources at most one level
- Only use a child resource if it's 100% clear that this can really only make sense and/or retrieved in the context
of the parent resource
product_ratingsounds like a good candidate for a nested resource... but what about querying all ratings of a particular user?
Chapter 7 - HTML Templates
- Build HTML views with the correct semantic tags
- This will result in easier to change views (tree of meaningful tags vs div hell)
- It will be easier to test since the semantic meaning of a page elemnt is more unlikely to change than a CSS class
- Solve layout / appearance problems with added
div/spantags and CSS
- Expose one instance variable per action (representing the resource) if possible
- Avoid representing the resource with several variables
- If you add additional non-resource instance variables you have to go check the controller to know how it was assigned
- Decorators/View Models are also no good choice since they make code harder to understand
- Exceptions are things like
@current_userand@country_codesor other UI state like@current_tab
- Use only instance variables in views not helpers directly if possible
- You can generalize/abstract code at the controller level to make it DRY
- If you only use instance variables in views you know exactly where to check for their values - in the controller
- Layouts should be used for global concerns like stylesheets or a sidewide navigation bar
- Use Partials for only re-usable components
- Use only locals inside not instance variables to keep it re-usable in any situation
- Just use ERB (and not Haml or Slim etc) since it's closer to HTML and comes with Rails
Chapter 8 - Helpers
- Helpers introduce lots of "global view code" which can be a problem for maintainability
- Be careful to not put "view concerns" into helper functions which are actually domain concerns since they are not just
an incidental display format but the User relies on that in their daily job
- i.e. a specially formatted Item ID
- Good users for helpers
- Global UI context like
current_user - Wrapping often used UI Component partials
- Directly rendering HTML to act as very simple small UI components is also ok!
- Global UI context like
- Define UI Components helpers only in
application_helper.rb- Separation in several helper files does not really help the fact that all helpers are global
- It's better to express that fact by just writing everything in application_helper
- Define global UI state that needs to access database (like
current_user) as privateApplicationControllermethods and turn it into a helper method withhelper :current_useretc. - Alternative method: Presenters
- Wrap your domain object into an object that adds a few methods for views and delegates the rest to the domain object
- This unfortunately introduces inconsistencies and more design decisions you have to make (should I make a Prresenter because it's everywhere even though I don't need it etc ?)
- it also makes it hard to exactly know the type an object has
- Few