About: MVC

Cross-cutting concerns: Logically centralized but may appear multiple places in implementation.

How to share cross-cutting concerns in program.

Aspect-Oriented Programming

Advice is a specific piece of code that implements a cross-cutting concern.
Pointcuts are the places we want to “inject” advice at runtime.

Advice + Pointcut = Aspect

Rails Examples

Validation (for model)

Validation is advice in AOP sense, specifying declaratively in model class. Rails 的验证(validation)是固定阶段自动运行的,而回调(callback)是我们可以在各个阶段插入自定义行为的钩子。

Controller filter (for controller)

Compare to validation, a filter can take the power of controller and stop the show immediately.

Example:

NOTE: Use :only and :except symbol to specify the action you want to filter.

Summary

Partial (for view)

Reuse Partials

We can move the form into a file called app/views/products/_form.html.erb. The filename starts with an underscore to denote this is a partial.

<!-- Use local variable to reuse in page for multiple times! -->
<%= form_with model: product do |form| %>
  <div>
    <%= form.label :name %>
    <%= form.text_field :name %>
  </div>
 
  <div>
    <%= form.submit %>
  </div>
<% end %>

To use this partial in our app/views/products/new.html.erb view, we can replace the form with a render call:

<h1>New product</h1>
 
<%= render "form", product: @product %>
<%= link_to "Cancel", products_path %>

A partial may be in a different directory than the view that uses it, in which case a path such as layouts/footer would cause Rails to look for app/views/layouts/ _footer.html.erb.

指向原始笔记的链接

Building Queries with Reusable Scopes

The one below is recommended.

Summary