Fizzy のソースから見る Basecamp 流 Rails の書き方
きっかけ
Basecamp (37signals) が Fizzy という OSS の Rails プロジェクトを公開していますが、
それに関連して DHH 先生が、Stimulus と Hotwire を使うことで最小限の JS (CSS の方が行数が多いくらい) で動いて最高に楽しいぜ! と自画自賛してたので、ちょっと興味が出て中を覗いてみました。
といっても、Basecamp および DHH がどのように Rails を書いているのか、という観点でも以前から少し気になっていたので、
本記事では、JS 周りだけでなく、アプリケーションの全体像をコードリーディングしてまとめました。
Fizzy とは?
Fizzy は、カンバンアプリです。
ライセンスは独自ライセンスの O’Saasy License というもので、基本的に自由に使ってよいが、これをそのまま使用して同様の SaaS サービスを競合して展開することを禁止する条項が含まれていました。
起動してみる。
git pull した後、Ruby のバージョンが私の環境は最新ではなくて少しつまづきましたが、
$ bin/setup
$ bin/dev
で起動できました。

バージョン
2025/12/9 時点の main ブランチ( da2bd2f2e ) で動かして確認しました。
| 対象 | バージョン |
|---|---|
| Ruby | 3.4.7 |
| Rails | 8.2.0.alpha |
全体像
技術スタック
とりあえず気になったところだけ抜粋。
| カテゴリ | 使用ライブラリ |
|---|---|
| Assets | propshaft, importmap-rails |
| Frontend | stimulus-rails, turbo-rails |
| CSS Framework | 使用ライブラリなし。てっきり tailwind かと思いましたが、自前の CSS でした。BEM っぽい名前の付け方に見えたけど違った。(.card-columns__left など) |
| View template | ERB, jbuilder |
| Testing | minitest, capybara, selenium, webmock, vcr, mocha |
| DB | SQLite もしくは MySQL |
| 認証 | 使用ライブラリなし(rails g authentication で生成したものっぽい) |
| 管理画面 | 使用ライブラリなし |
Gemfile を見ましたが、素の Rails に近い感じでした。
ただ、Gemfile.saas という見慣れぬファイルがありました。
# This Gemfile extends the base Gemfile with SaaS-specific dependencies
eval_gemfile "Gemfile"
git_source(:bc) { |repo| "https://github.com/basecamp/#{repo}" }
# SaaS-only functionality
gem "activeresource", require: "active_resource"
gem "queenbee", bc: "queenbee-plugin"
gem "fizzy-saas", bc: "fizzy-saas"
gem "console1984", bc: "console1984"
gem "audits1984", bc: "audits1984"
# Telemetry
gem "rails_structured_logging", bc: "rails-structured-logging"
gem "sentry-ruby"
gem "sentry-rails"
gem "yabeda"
gem "yabeda-actioncable"
gem "yabeda-activejob", github: "basecamp/yabeda-activejob", branch: "bulk-and-scheduled-jobs"
gem "yabeda-gc"
gem "yabeda-http_requests"
gem "yabeda-prometheus-mmap"
gem "yabeda-puma-plugin"
gem "yabeda-rails"
gem "webrick" # required for yabeda-prometheus metrics server
gem "prometheus-client-mmap", "~> 1.3"
最初、Sass かと思いましたが、SaaS (Software as a Service) でした。SaaS として動かす際に読む用の Gemfile なのかな。とりあえず無視して読み進めます。
(eval_gemfile って初めて知った。)
module Fizzy
class << self
def saas?
return @saas if defined?(@saas)
@saas = !!(((ENV["SAAS"] || File.exist?(File.expand_path("../tmp/saas.txt", __dir__))) && ENV["SAAS"] != "false"))
end
def configure_bundle
if saas?
ENV["BUNDLE_GEMFILE"] = "Gemfile.saas"
end
end
end
フォルダ構成
フォルダ構成です。デフォルトから増えてるフォルダがありました。
| フォルダ | 用途 |
|---|---|
| script | Ruby か ShellScript で書かれた、いろんなスクリプト置き場 |
| script/maintenance | ActiveRecord を使用したメンテナンス用のスクリプト置き場。重複したタグの削除スクリプトなどがあった。 |
| script/migrations | 手動で行なうマイグレーション置き場のよう。ただ、db/migration のファイル でも SQL 直書きでマイグレーションしている箇所もあったので使い分けはどうしてるのかしら。 |
| lib/assets | 空 |
| lib/deployment | DatabaseResolver が定義されてました |
| lib/rails_ext | オープンクラスしたりなどの拡張ファイル置き場 |
| lib/web_push | web-push のラッパー置き場 |
$ tree -d --gitignore -L 2
.
├── app
│ ├── assets
│ ├── channels
│ ├── controllers
│ ├── helpers
│ ├── javascript
│ ├── jobs
│ ├── mailers
│ ├── models
│ └── views
├── bin
├── config
│ ├── environments
│ ├── initializers
│ └── locales
├── db
│ ├── migrate
│ └── seeds
├── lib
│ ├── assets
│ ├── deployment
│ ├── rails_ext
│ ├── tasks
│ └── web_push
├── log
├── public
│ └── audio
├── script
│ ├── maintenance
│ └── migrations
├── storage
├── test
│ ├── channels
│ ├── controllers
│ ├── fixtures
│ ├── helpers
│ ├── jobs
│ ├── lib
│ ├── mailers
│ ├── models
│ ├── system
│ └── test_helpers
├── tmp
│ ├── pids
│ └── storage
└── vendor
└── javascript
48 directories
$ rails stats
スタッツです。満遍なく使ってるようです。
$ bin/rails stats
+----------------------+--------+--------+---------+---------+-----+-------+
| Name | Lines | LOC | Classes | Methods | M/C | LOC/M |
+----------------------+--------+--------+---------+---------+-----+-------+
| Controllers | 1962 | 1601 | 88 | 290 | 3 | 3 |
| Helpers | 869 | 774 | 0 | 94 | 0 | 6 |
| Jobs | 126 | 100 | 13 | 12 | 0 | 6 |
| Models | 4745 | 3814 | 64 | 558 | 8 | 4 |
| Mailers | 67 | 58 | 5 | 6 | 1 | 7 |
| Channels | 22 | 19 | 1 | 3 | 3 | 4 |
| Views | 5196 | 4616 | 0 | 3 | 0 | 1536 |
| Stylesheets | 7839 | 6381 | 0 | 0 | 0 | 0 |
| JavaScript | 2931 | 2338 | 0 | 31 | 0 | 73 |
| Libraries | 401 | 277 | 6 | 36 | 6 | 5 |
| Controller tests | 3027 | 2351 | 83 | 258 | 3 | 7 |
| Helper tests | 192 | 152 | 4 | 27 | 6 | 3 |
| Job tests | 13 | 10 | 1 | 1 | 1 | 8 |
| Model tests | 4283 | 3263 | 76 | 370 | 4 | 6 |
| Mailer tests | 176 | 146 | 9 | 17 | 1 | 6 |
| Channel tests | 36 | 27 | 1 | 3 | 3 | 7 |
| System tests | 100 | 74 | 1 | 7 | 7 | 8 |
+----------------------+--------+--------+---------+---------+-----+-------+
| Total | 31985 | 26001 | 352 | 1716 | 4 | 13 |
+----------------------+--------+--------+---------+---------+-----+-------+
Code LOC: 19978 Test LOC: 6023 Code to Test Ratio: 1:0.3
コードリーディング
では、コードリーディングしていきます。
app/javascript
まず、最初は app/javascript から見ていきたいと思います。
何があるか確認してみます。
$ tree app/javascript/
app/javascript/
├── application.js
├── controllers
│ ├── application.js
│ ├── auto_click_controller.js
│ ├── auto_save_controller.js
│ ├── auto_submit_controller.js
│ ├── autoresize_controller.js
│ ├── badge_controller.js
│ ├── bar_controller.js
│ ├── beacon_controller.js
│ ├── boards_form_controller.js
│ ├── bubble_controller.js
│ ├── clicker_controller.js
│ ├── collapsible_columns_controller.js
│ ├── combobox_controller.js
│ ├── copy_to_clipboard_controller.js
│ ├── css_variable_counter_controller.js
│ ├── details_controller.js
│ ├── dialog_controller.js
│ ├── dialog_manager_controller.js
│ ├── drag_and_drop_controller.js
│ ├── drag_and_strum_controller.js
│ ├── element_removal_controller.js
│ ├── fetch_on_visible_controller.js
│ ├── filter_controller.js
│ ├── filter_form_controller.js
│ ├── filter_settings_controller.js
│ ├── form_controller.js
│ ├── frame_controller.js
│ ├── frame_reloader_controller.js
│ ├── hotkey_controller.js
│ ├── index.js
│ ├── knob_controller.js
│ ├── lightbox_controller.js
│ ├── local_save_controller.js
│ ├── local_time_controller.js
│ ├── magic_link_controller.js
│ ├── multi_selection_combobox_controller.js
│ ├── nav_section_expander_controller.js
│ ├── navigable_list_controller.js
│ ├── notifications_controller.js
│ ├── notifications_tray_controller.js
│ ├── outlet_auto_save_controller.js
│ ├── pagination_controller.js
│ ├── reaction_delete_controller.js
│ ├── reaction_emoji_controller.js
│ ├── related_element_controller.js
│ ├── retarget_links_controller.js
│ ├── soft_keyboard_controller.js
│ ├── syntax_highlight_controller.js
│ ├── timezone_cookie_controller.js
│ ├── toggle_class_controller.js
│ ├── toggle_enable_controller.js
│ ├── tooltip_controller.js
│ ├── turbo_navigation_controller.js
│ └── upload_preview_controller.js
├── helpers
│ ├── date_helpers.js
│ ├── form_helpers.js
│ ├── html_helpers.js
│ ├── http_helpers.js
│ ├── orientation_helpers.js
│ ├── scroll_helpers.js
│ ├── text_helpers.js
│ └── timing_helpers.js
└── initializers
├── current.js
└── index.js
4 directories, 65 files
めっちゃある。
app/javascript/application.js
app/javascript には、
- controllers
- helpers
- initializers
の3つのフォルダがありましたが、helpers は application.js では読み込んでいませんでした。
import "@hotwired/turbo-rails"
import "initializers"
import "controllers"
import "lexxy"
import "@rails/actiontext"
app/javascript/helpers/xxx_helpers.js
その application.js で読み込まれていなかった helpers は、便利関数の置き場でした。
export function differenceInDays(fromDate, toDate) {
return Math.round(Math.abs((beginningOfDay(toDate) - beginningOfDay(fromDate)) / (1000 * 60 * 60 * 24)))
}
export function signedDifferenceInDays(fromDate, toDate) {
return Math.round((beginningOfDay(toDate) - beginningOfDay(fromDate)) / (1000 * 60 * 60 * 24))
}
export function beginningOfDay(date) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate())
}
export function secondsToDate(seconds) {
return new Date(seconds * 1000)
}
controllers 側で、import して使用しています。
import { Controller } from "@hotwired/stimulus"
import { signedDifferenceInDays } from "helpers/date_helpers"
app/javascript/initializers/xxx.js
initializers は、名前からして初期化処理のようですが、現状は window オブジェクトに Current を生やす1ファイルのみでした。
たぶん、controllers に置けない処理はここに置くのかなと思います。
import "initializers/current"
class Current {
get user() {
const currentUserId = this.#extractContentFromMetaTag("current-user-id")
if (currentUserId) {
return { id: currentUserId }
}
}
#extractContentFromMetaTag(name) {
return document.head.querySelector(`meta[name="${name}"]`)?.getAttribute("content")
}
}
window.Current = new Current()
app/javascript/controllers/xxx_controller.js
普通の Stimulus なので、controllers の JavaScript 自体で特に語ることは無いんですが、
View ファイルを見ると、data-controller が入れ子になっている箇所(data-controller="dialog" 内の data-controller="tooltip")があり、結構なんでも controllers に書いてるようです。
<div data-controller="dialog" data-dialog-modal-value="true" class="flex-inline">
<%= tag.button class: "btn", data: { action: "dialog#open", controller: "tooltip" } do %>
<%= icon_tag "qr-code" %>
<span class="for-screen-reader">Display auto-login QR code</span>
<% end %>
<dialog class="dialog panel shadow" data-dialog-target="dialog">
<%= qr_code_image(url) %>
<form method="dialog" class="margin-block-start flex justify-center">
<button class="btn" data-controller="tooltip">
<%= icon_tag "remove" %>
<span class="for-screen-reader">Close dialog</span>
</button>
</form>
</dialog>
</div>
その data-controller="tooltip" の処理です。
(一瞬混乱しましたが、多分 static targets = [ "tooltip" ] は不要な行だと思われ)
import { Controller } from "@hotwired/stimulus"
import { orient } from "helpers/orientation_helpers"
export default class extends Controller {
static targets = [ "tooltip" ]
connect() {
this.element.addEventListener("mouseenter", this.mouseEnter.bind(this))
this.element.addEventListener("mouseout", this.mouseOut.bind(this))
}
disconnect() {
this.element.removeEventListener("mouseenter", this.mouseEnter.bind(this))
this.element.removeEventListener("mouseout", this.mouseOut.bind(this))
}
mouseEnter(event) {
orient(this.#tooltipElement)
}
mouseOut(event) {
orient(this.#tooltipElement, false)
}
get #tooltipElement() {
return this.element.querySelector(".for-screen-reader")
}
get #tooltipText() {
return this.#tooltipElement.innerText
}
}
app/models
次は、モデルを見ていきます。
何があるか確認してみます。
$ tree app/models
app/models/
├── access.rb
├── account
│ ├── entropic.rb
│ ├── export.rb
│ ├── external_id_sequence.rb
│ ├── join_code.rb
│ ├── seedeable.rb
│ └── seeder.rb
├── account.rb
├── application_platform.rb
├── application_record.rb
├── assignment.rb
├── board
│ ├── accessible.rb
│ ├── auto_postponing.rb
│ ├── broadcastable.rb
│ ├── cards.rb
│ ├── entropic.rb
│ ├── publication.rb
│ ├── publishable.rb
│ └── triageable.rb
├── board.rb
├── card
│ ├── activity_spike
│ │ └── detector.rb
│ ├── activity_spike.rb
│ ├── assignable.rb
│ ├── broadcastable.rb
│ ├── closeable.rb
│ ├── colored.rb
│ ├── engagement.rb
│ ├── entropic.rb
│ ├── entropy.rb
│ ├── eventable
│ │ └── system_commenter.rb
│ ├── eventable.rb
│ ├── exportable.rb
│ ├── golden.rb
│ ├── goldness.rb
│ ├── mentions.rb
│ ├── multistep.rb
│ ├── not_now.rb
│ ├── pinnable.rb
│ ├── postponable.rb
│ ├── promptable.rb
│ ├── readable.rb
│ ├── searchable.rb
│ ├── stallable.rb
│ ├── statuses.rb
│ ├── taggable.rb
│ ├── triageable.rb
│ └── watchable.rb
├── card.rb
├── closure.rb
├── color.rb
├── column
│ ├── colored.rb
│ └── positioned.rb
├── column.rb
├── comment
│ ├── eventable.rb
│ ├── mentions.rb
│ ├── promptable.rb
│ └── searchable.rb
├── comment.rb
├── concerns
│ ├── attachments.rb
│ ├── eventable.rb
│ ├── filterable.rb
│ ├── mentions.rb
│ ├── notifiable.rb
│ ├── push_notifiable.rb
│ └── searchable.rb
├── current.rb
├── entropy.rb
├── event
│ ├── description.rb
│ ├── particulars.rb
│ └── promptable.rb
├── event.rb
├── filter
│ ├── fields.rb
│ ├── params.rb
│ ├── resources.rb
│ └── summarized.rb
├── filter.rb
├── identity
│ ├── joinable.rb
│ └── transferable.rb
├── identity.rb
├── magic_link
│ └── code.rb
├── magic_link.rb
├── mention.rb
├── notification
│ └── bundle.rb
├── notification.rb
├── notification_pusher.rb
├── notifier
│ ├── card_event_notifier.rb
│ ├── comment_event_notifier.rb
│ └── mention_notifier.rb
├── notifier.rb
├── pin.rb
├── push
│ └── subscription.rb
├── push.rb
├── qr_code_link.rb
├── reaction.rb
├── search
│ ├── highlighter.rb
│ ├── query.rb
│ ├── record
│ │ ├── sqlite
│ │ │ └── fts.rb
│ │ ├── sqlite.rb
│ │ └── trilogy.rb
│ ├── record.rb
│ ├── result.rb
│ └── stemmer.rb
├── search.rb
├── session.rb
├── signup
│ └── account_name_generator.rb
├── signup.rb
├── ssrf_protection.rb
├── step.rb
├── tag
│ └── attachable.rb
├── tag.rb
├── tagging.rb
├── time_window_parser.rb
├── user
│ ├── accessor.rb
│ ├── assignee.rb
│ ├── attachable.rb
│ ├── avatar.rb
│ ├── configurable.rb
│ ├── day_timeline
│ │ ├── column.rb
│ │ └── serializable.rb
│ ├── day_timeline.rb
│ ├── email_address_changeable.rb
│ ├── filtering.rb
│ ├── mentionable.rb
│ ├── named.rb
│ ├── notifiable.rb
│ ├── role.rb
│ ├── searcher.rb
│ ├── settings.rb
│ ├── timelined.rb
│ ├── transferable.rb
│ └── watcher.rb
├── user.rb
├── watch.rb
├── webhook
│ ├── delinquency_tracker.rb
│ ├── delivery.rb
│ └── triggerable.rb
└── webhook.rb
24 directories, 137 files
ビジネスロジックも、Decorator 的なものも、全部モデルに入っていました。
ファイル名を見ただけでは判別できませんが、app/models に入っているのは以下のパターンのいずれかになります。
| No. | ファイル | 概要 |
|---|---|---|
| 1 | app/models/[record_name].rb |
ApplicationRecord を継承した一般的なモデル |
| 2 | app/models/[record_name]/[module_name].rb | モデル特有のミックスイン置き場。ActiveRecord の処理だけでなく、Decorator として使用しているものもあり。 |
| 3 | app/models/[record_name]/[record_name].rb | ネームスペース付きの ApplicationRecord を継承したモデル |
| 4 | app/models/[module_name].rb | ネームスペースを作るための Module |
| 5 | app/models/[module_name]/[record_name].rb | ネームスペース付きの ApplicationRecord を継承したモデル |
| 6 | app/models/[class_name].rb | 素の Ruby クラス。いわゆる PORO。Module を extend self しているものもあった。 |
| 7 | app/models/[form_object].rb |
include ActiveModel::Model しているモデル |
| 8 | app/models/concerns/[module_name].rb | 各モデルで共有する concerns 置き場。一般的なそれと変わりなし。 |
| 9 | app/models/current.rb |
ActiveSupport::CurrentAttributes を継承した Current モデル |
1. app/models/[record_name].rb
ApplicationRecord を継承した一般的なモデル。特に変わったところはないかなと思いましたが、
-
Filterableが app/models/concerns/filterable.rb- (※後述
8. app/models/concerns/[module_name].rbのバターン)
- (※後述
-
Attachableが app/models/tag/attachable.rb- (※後述
2. app/models/[record_name]/[module_name].rbのバターン)
- (※後述
と同じ行で include していました。指す場所が違って混乱しそうですが、特に気にしないのかな。
class Tag < ApplicationRecord
include Attachable, Filterable
belongs_to :account, default: -> { Current.account }
has_many :taggings, dependent: :destroy
has_many :cards, through: :taggings
validates :title, format: { without: /\A#/ }
normalizes :title, with: -> { it.downcase }
scope :alphabetically, -> { order("lower(title)") }
scope :unused, -> { left_outer_joins(:taggings).where(taggings: { id: nil }) }
def hashtag
"#" + title
end
def cards_count
cards.open.count
end
end
2. app/models/[record_name]/[module_name].rb
モデル特有のミックスインです。
名前の付け方は、-able で終わったり終わらなかったり。自由な感じ。
class User < ApplicationRecord
include Accessor, Assignee, Attachable, Avatar, Configurable, EmailAddressChangeable,
Mentionable, Named, Notifiable, Role, Searcher, Watcher
include Timelined # Depends on Accessor
# 略
end
ActiveRecord のアソシエーションが定義されてるパターン
User とか Card とかの明らかに太りやすそうなモデル以外も、割と積極的に分割してる感じでした。
(configurable.rb という名前で、user_settings と push_subscriptions テーブルを関連付けてて混乱しないのかな)
module User::Configurable
extend ActiveSupport::Concern
included do
has_one :settings, class_name: "User::Settings", dependent: :destroy
has_many :push_subscriptions, class_name: "Push::Subscription", dependent: :delete_all
after_create :create_settings, unless: :system?
delegate :timezone, to: :settings, allow_nil: true
end
def in_time_zone(&block)
Time.use_zone(timezone, &block)
end
end
Decorator として使用しているパターン
module User::Named
extend ActiveSupport::Concern
included do
scope :alphabetically, -> { order("lower(name)") }
end
def first_name
name.split(/\s/).first
end
def last_name
name.split(/\s/, 2).last
end
def initials
name.scan(/\b\p{L}/).join.upcase
end
def familiar_name
names = name.split
return name if names.length == 1
"#{names.first} #{names[1..].map { |n| "#{n[0]}." }.join}"
end
end
3. app/models/[record_name]/[record_name].rb
user_settings テーブルとの ORM など。まあ、普通っぽい見た目ですが、
User::Settings って複数形だ。これ以外のモデルは単数形なんですが。気にならないのかな。
class User::Settings < ApplicationRecord
belongs_to :account, default: -> { user.account }
belongs_to :user
enum :bundle_email_frequency, %i[ never every_few_hours daily weekly ],
default: :every_few_hours, prefix: :bundle_email
after_update :review_pending_bundles, if: :saved_change_to_bundle_email_frequency?
# 略
end
4. app/models/[module_name].rb
単にネームスペースを切るためだけのファイルでした。
module Push
def self.table_name_prefix
"push_"
end
end
5. app/models/[module_name]/[record_name].rb
やってることは 3. app/models/[record_name]/[record_name].rb と同じです。
class Push::Subscription < ApplicationRecord
PERMITTED_ENDPOINT_HOSTS = %w[
fcm.googleapis.com
updates.push.services.mozilla.com
web.push.apple.com
notify.windows.com
].freeze
belongs_to :account, default: -> { user.account }
belongs_to :user
validates :endpoint, presence: true
validate :validate_endpoint_url
# 略
end
6. app/models/[class_name].rb
素の Ruby クラス。いわゆる PORO。
class QrCodeLink
attr_reader :url
class << self
def from_signed(signed)
new verifier.verify(signed, purpose: :qr_code)
end
def verifier
ActiveSupport::MessageVerifier.new(secret, url_safe: true)
end
private
def secret
Rails.application.key_generator.generate_key("qr_codes")
end
end
def initialize(url)
@url = url
end
def signed
self.class.verifier.generate(@url, purpose: :qr_code)
end
end
Module を extend self しているものもあった。
module SsrfProtection
extend self
DNS_RESOLUTION_TIMEOUT = 2
DNS_NAMESERVERS = %w[
1.1.1.1
8.8.8.8
]
DISALLOWED_IP_RANGES = [
IPAddr.new("0.0.0.0/8"), # "This" network (RFC1700)
IPAddr.new("100.64.0.0/10"), # Carrier-grade NAT (RFC6598)
IPAddr.new("198.18.0.0/15") # Benchmark testing (RFC2544)
].freeze
def resolve_public_ip(hostname)
ip_addresses = resolve_dns(hostname)
public_ips = ip_addresses.reject { |ip| private_address?(ip) }
public_ips.sort_by { |ipaddr| ipaddr.ipv4? ? 0 : 1 }.first&.to_s
end
# 略
end
7. app/models/[form_object].rb
FormObject として使用しているのは、app/models/signup.rb の1つだけでした。
class Signup
include ActiveModel::Model
include ActiveModel::Attributes
include ActiveModel::Validations
attr_accessor :full_name, :email_address, :identity
attr_reader :account, :user
validates :email_address, format: { with: URI::MailTo::EMAIL_REGEXP }, on: :identity_creation
validates :full_name, :identity, presence: true, on: :completion
# 略
end
signups_controller.rb 等で呼ばれていました。
class SignupsController < ApplicationController
# 略
def new
@signup = Signup.new
end
def create
signup = Signup.new(signup_params)
if signup.valid?(:identity_creation)
redirect_to_session_magic_link signup.create_identity
else
head :unprocessable_entity
end
end
# 略
8. app/models/concerns/[module_name].rb
名前は基本的に -able で終わってました。使い方も普通な感じです。
module Notifiable
extend ActiveSupport::Concern
included do
has_many :notifications, as: :source, dependent: :destroy
after_create_commit :notify_recipients_later
end
def notify_recipients
Notifier.for(self)&.notify
end
def notifiable_target
self
end
private
def notify_recipients_later
NotifyRecipientsJob.perform_later self
end
end
9. app/models/current.rb
session, user, account あたりは、一般的かなと思いますが、
http_method, request_id, user_agent, ip_address, referrer も Current に突っ込むんだ。
class Current < ActiveSupport::CurrentAttributes
attribute :session, :user, :account
attribute :http_method, :request_id, :user_agent, :ip_address, :referrer
delegate :identity, to: :session, allow_nil: true
def session=(value)
super(value)
if value.present? && account.present?
self.user = identity.users.find_by(account: account)
end
end
def with_account(value, &)
with(account: value, &)
end
def without_account(&)
with(account: nil, &)
end
end
Controller の Concern で自動的に入れるようになってました。
(Current.ip_address 等は、いまのところ Signup モデルでしか使用していませんでした。)
module CurrentRequest
extend ActiveSupport::Concern
included do
before_action do
Current.http_method = request.method
Current.request_id = request.uuid
Current.user_agent = request.user_agent
Current.ip_address = request.ip
Current.referrer = request.referrer
end
end
end
以上がモデルです。
app/controllers
次は、コントローラを見ていきます。
何があるか確認してみます。
$ tree app/controllers/
app/controllers/
├── account
│ ├── entropies_controller.rb
│ ├── exports_controller.rb
│ ├── join_codes_controller.rb
│ └── settings_controller.rb
├── admin
│ └── stats_controller.rb
├── admin_controller.rb
├── application_controller.rb
├── boards
│ ├── columns
│ │ ├── closeds_controller.rb
│ │ ├── not_nows_controller.rb
│ │ └── streams_controller.rb
│ ├── columns_controller.rb
│ ├── entropies_controller.rb
│ ├── involvements_controller.rb
│ └── publications_controller.rb
├── boards_controller.rb
├── cards
│ ├── assignments_controller.rb
│ ├── boards_controller.rb
│ ├── closures_controller.rb
│ ├── columns_controller.rb
│ ├── comments
│ │ └── reactions_controller.rb
│ ├── comments_controller.rb
│ ├── engagements_controller.rb
│ ├── goldnesses_controller.rb
│ ├── images_controller.rb
│ ├── not_nows_controller.rb
│ ├── pins_controller.rb
│ ├── previews_controller.rb
│ ├── publishes_controller.rb
│ ├── readings_controller.rb
│ ├── steps_controller.rb
│ ├── taggings_controller.rb
│ ├── triages_controller.rb
│ └── watches_controller.rb
├── cards_controller.rb
├── columns
│ ├── cards
│ │ └── drops
│ │ ├── closures_controller.rb
│ │ ├── columns_controller.rb
│ │ ├── not_nows_controller.rb
│ │ └── streams_controller.rb
│ ├── left_positions_controller.rb
│ └── right_positions_controller.rb
├── concerns
│ ├── authentication.rb
│ ├── authorization.rb
│ ├── block_search_engine_indexing.rb
│ ├── board_scoped.rb
│ ├── card_scoped.rb
│ ├── column_scoped.rb
│ ├── current_request.rb
│ ├── current_timezone.rb
│ ├── day_timelines_scoped.rb
│ ├── filter_scoped.rb
│ ├── request_forgery_protection.rb
│ ├── routing_headers.rb
│ ├── set_platform.rb
│ ├── turbo_flash.rb
│ └── view_transitions.rb
├── events
│ ├── day_timeline
│ │ └── columns_controller.rb
│ └── days_controller.rb
├── events_controller.rb
├── filters
│ └── settings_refreshes_controller.rb
├── filters_controller.rb
├── join_codes_controller.rb
├── landings_controller.rb
├── my
│ ├── menus_controller.rb
│ ├── pins_controller.rb
│ └── timezones_controller.rb
├── notifications
│ ├── bulk_readings_controller.rb
│ ├── readings_controller.rb
│ ├── settings_controller.rb
│ ├── trays_controller.rb
│ └── unsubscribes_controller.rb
├── notifications_controller.rb
├── prompts
│ ├── boards
│ │ └── users_controller.rb
│ ├── cards_controller.rb
│ ├── tags_controller.rb
│ └── users_controller.rb
├── public
│ ├── base_controller.rb
│ ├── boards
│ │ ├── columns
│ │ │ ├── closeds_controller.rb
│ │ │ ├── not_nows_controller.rb
│ │ │ └── streams_controller.rb
│ │ └── columns_controller.rb
│ ├── boards_controller.rb
│ └── cards_controller.rb
├── pwa_controller.rb
├── qr_codes_controller.rb
├── searches
│ └── queries_controller.rb
├── searches_controller.rb
├── sessions
│ ├── magic_links_controller.rb
│ ├── menus_controller.rb
│ └── transfers_controller.rb
├── sessions_controller.rb
├── signups
│ └── completions_controller.rb
├── signups_controller.rb
├── users
│ ├── avatars_controller.rb
│ ├── email_addresses
│ │ └── confirmations_controller.rb
│ ├── email_addresses_controller.rb
│ ├── events_controller.rb
│ ├── joins_controller.rb
│ ├── push_subscriptions_controller.rb
│ ├── roles_controller.rb
│ └── verifications_controller.rb
├── users_controller.rb
├── webhooks
│ └── activations_controller.rb
└── webhooks_controller.rb
27 directories, 103 files
app/controllers/xxx_controller.rb
Scaffold で作ったようなすっきりした見た目です。
特に気になるところはなかったんですが、# GET /boards などのコメント行が無いのが少し気になりました。
class BoardsController < ApplicationController
include FilterScoped
before_action :set_board, except: %i[ new create ]
before_action :ensure_permission_to_admin_board, only: %i[ update destroy ]
def show
if @filter.used?(ignore_boards: true)
show_filtered_cards
else
show_columns
end
end
def new
@board = Board.new
end
def create
@board = Board.create! board_params.with_defaults(all_access: true)
redirect_to board_path(@board)
end
def edit
selected_user_ids = @board.users.pluck :id
@selected_users, @unselected_users = \
@board.account.users.active.alphabetically.includes(:identity).partition { |user| selected_user_ids.include? user.id }
end
def update
@board.update! board_params
@board.accesses.revise granted: grantees, revoked: revokees if grantees_changed?
if @board.accessible_to?(Current.user)
redirect_to edit_board_path(@board), notice: "Saved"
else
redirect_to root_path, notice: "Saved (you were removed from the board)"
end
end
def destroy
@board.destroy
redirect_to root_path
end
private
def set_board
@board = Current.user.boards.find params[:id]
end
# 略
end
URLのコメント行をわざわざ消してるのか、コピペか、手書きで一から書いているのか、
$ bin/rails app:templates:copy をすると、lib/templates にジェネレータ用のテンプレートが生成されるので私はたまに使うのですが、lib/templates は空でした。
試しに $ bin/rails d scaffold Post title content:text するとコメント行ありのデフォルトのまま生成された。
Scaffold ジェネレータはあまり使ってないのかもですね。
class PostsController < ApplicationController
before_action :set_post, only: %i[ show edit update destroy ]
# GET /posts or /posts.json
def index
@posts = Post.all
end
# GET /posts/1 or /posts/1.json
def show
end
# 略
app/controllers/[scope_name]/xxx_controller.rb
ネストしたコントローラについて。
DHH の Gist に documents.rb というのがあり、そこに普段どう作っているのか書いているので XxxScoped で Concern に切り出しているのは以前から知っていましたが、それと同じことをしていました。
class Cards::StepsController < ApplicationController
include CardScoped
before_action :set_step, only: %i[ show edit update destroy ]
def create
@step = @card.steps.create!(step_params)
end
def show
end
def edit
end
def update
@step.update!(step_params)
end
def destroy
@step.destroy!
end
private
def set_step
@step = @card.steps.find(params[:id])
end
def step_params
params.expect(step: [ :content, :completed ])
end
end
index, show, new, edit, create, update, destroy 以外のアクションはあるか?
「DHHはどのようにRailsのコントローラを書くのか」という 2016年の記事で、デフォルトアクション以外を書きそうになったら、そこにリソース名を見つけて、REST に従うという旨が述べられていましたが、
実際にそうなのでしょうか。Rails console で確認してみます。
irb> Rails.application.eager_load!
irb> ApplicationController.descendants.select{|controller|
(controller.instance_methods(false) - %i[index show new edit create update destroy]).any?
}
=> [PwaController, MissionControl::Jobs::ApplicationController]
おお。本当だった。
例外が2つだけありましたが、中を見るとリソースではありませんでした。
app/controllers/concerns/authentication.rb
認証について。これは $ rails g authentication で生成されるのとほとんど同じだったので説明は割愛します。
以下参考URLです。
module Authentication
extend ActiveSupport::Concern
included do
before_action :require_account # Checking and setting account must happen first
before_action :require_authentication
after_action :ensure_development_magic_link_not_leaked
helper_method :authenticated?
etag { Current.session.id if authenticated? }
include LoginHelper
end
class_methods do
def require_unauthenticated_access(**options)
allow_unauthenticated_access **options
before_action :redirect_authenticated_user, **options
end
# 略
app/views
次は、ビューを見ていきます。
何があるか確認してみます。
$ tree app/views
app/views/
├── account
│ ├── exports
│ │ └── show.html.erb
│ ├── join_codes
│ │ ├── edit.html.erb
│ │ └── show.html.erb
│ └── settings
│ ├── _entropy.html.erb
│ ├── _export.html.erb
│ ├── _name.html.erb
│ ├── _user.html.erb
│ ├── _users.html.erb
│ └── show.html.erb
├── action_text
│ └── attachables
│ ├── _remote_image.html.erb
│ └── _remote_video.html.erb
├── active_storage
│ └── blobs
│ ├── _blob.html.erb
│ └── web
│ └── _representation.html.erb
├── admin
│ └── stats
│ └── show.html.erb
├── bar
│ └── _bar.html.erb
├── boards
│ ├── _access_toggle.html.erb
│ ├── _board.json.jbuilder
│ ├── columns
│ │ ├── _empty_placeholder.html.erb
│ │ ├── _list.html.erb
│ │ ├── closeds
│ │ │ └── show.html.erb
│ │ ├── create.turbo_stream.erb
│ │ ├── destroy.turbo_stream.erb
│ │ ├── not_nows
│ │ │ └── show.html.erb
│ │ ├── show.html.erb
│ │ ├── streams
│ │ │ └── show.html.erb
│ │ └── update.turbo_stream.erb
│ ├── edit
│ │ ├── _auto_close.html.erb
│ │ ├── _delete.html.erb
│ │ ├── _name.html.erb
│ │ ├── _publication.html.erb
│ │ └── _users.html.erb
│ ├── edit.html.erb
│ ├── entropies
│ │ └── update.turbo_stream.erb
│ ├── involvements
│ │ └── update.html.erb
│ ├── new.html.erb
│ ├── publications
│ │ ├── create.turbo_stream.erb
│ │ └── destroy.turbo_stream.erb
│ ├── show
│ │ ├── _closed.html.erb
│ │ ├── _column.html.erb
│ │ ├── _columns.html.erb
│ │ ├── _expander.html.erb
│ │ ├── _filtered_cards.html.erb
│ │ ├── _mobile_columns.html.erb
│ │ ├── _not_now.html.erb
│ │ ├── _stream.html.erb
│ │ └── menu
│ │ ├── _column.html.erb
│ │ ├── _column_form.html.erb
│ │ ├── _columns.html.erb
│ │ └── _maximize.html.erb
│ └── show.html.erb
├── cards
│ ├── _broadcasts.html.erb
│ ├── _card.json.jbuilder
│ ├── _container.html.erb
│ ├── _delete.html.erb
│ ├── _messages.html.erb
│ ├── assignments
│ │ ├── _user.html.erb
│ │ ├── create.turbo_stream.erb
│ │ └── new.html.erb
│ ├── boards
│ │ └── edit.html.erb
│ ├── columns
│ │ ├── _column.html.erb
│ │ └── edit.html.erb
│ ├── comments
│ │ ├── _comment.html.erb
│ │ ├── _comment.json.jbuilder
│ │ ├── _new.html.erb
│ │ ├── _watchers.html.erb
│ │ ├── create.turbo_stream.erb
│ │ ├── destroy.turbo_stream.erb
│ │ ├── edit.html.erb
│ │ ├── reactions
│ │ │ ├── _menu.html.erb
│ │ │ ├── _reaction.html.erb
│ │ │ ├── _reactions.html.erb
│ │ │ ├── create.turbo_stream.erb
│ │ │ ├── destroy.turbo_stream.erb
│ │ │ ├── index.html.erb
│ │ │ └── new.html.erb
│ │ ├── show.html.erb
│ │ └── update.turbo_stream.erb
│ ├── container
│ │ ├── _closure.html.erb
│ │ ├── _closure_buttons.html.erb
│ │ ├── _content.html.erb
│ │ ├── _content_display.html.erb
│ │ ├── _gild.html.erb
│ │ ├── _image.html.erb
│ │ ├── _save_button.html.erb
│ │ └── footer
│ │ ├── _draft.html.erb
│ │ └── _published.html.erb
│ ├── display
│ │ ├── _preview.html.erb
│ │ ├── _previews.html.erb
│ │ ├── _public_preview.html.erb
│ │ ├── _public_previews.html.erb
│ │ ├── common
│ │ │ ├── _assignees.html.erb
│ │ │ ├── _background.html.erb
│ │ │ ├── _board.html.erb
│ │ │ └── _meta.html.erb
│ │ ├── mini
│ │ │ ├── _assignees.html.erb
│ │ │ ├── _meta.html.erb
│ │ │ └── _tags.html.erb
│ │ ├── perma
│ │ │ ├── _assignees.html.erb
│ │ │ ├── _background.html.erb
│ │ │ ├── _board.html.erb
│ │ │ ├── _meta.html.erb
│ │ │ ├── _steps.html.erb
│ │ │ └── _tags.html.erb
│ │ ├── preview
│ │ │ ├── _assignees.html.erb
│ │ │ ├── _board.html.erb
│ │ │ ├── _bubble.html.erb
│ │ │ ├── _columns.html.erb
│ │ │ ├── _meta.html.erb
│ │ │ ├── _people.html.erb
│ │ │ ├── _steps.html.erb
│ │ │ └── _tags.html.erb
│ │ └── public_preview
│ │ ├── _columns.html.erb
│ │ └── _meta.html.erb
│ ├── edit.html.erb
│ ├── index.html.erb
│ ├── pins
│ │ ├── _pin_button.html.erb
│ │ └── show.html.erb
│ ├── previews
│ │ └── index.turbo_stream.erb
│ ├── readings
│ │ └── create.turbo_stream.erb
│ ├── show.html.erb
│ ├── steps
│ │ ├── _step.html.erb
│ │ ├── create.turbo_stream.erb
│ │ ├── destroy.turbo_stream.erb
│ │ ├── edit.html.erb
│ │ ├── show.html.erb
│ │ └── update.turbo_stream.erb
│ ├── taggings
│ │ ├── _tag.html.erb
│ │ ├── create.turbo_stream.erb
│ │ └── new.html.erb
│ ├── triage
│ │ └── _columns.html.erb
│ ├── update.turbo_stream.erb
│ └── watches
│ ├── _refresh.turbo_stream.erb
│ ├── _watch_button.html.erb
│ ├── create.turbo_stream.erb
│ ├── destroy.turbo_stream.erb
│ └── show.html.erb
├── columns
│ ├── _column.json.jbuilder
│ ├── cards
│ │ └── drops
│ │ ├── closures
│ │ │ └── create.turbo_stream.erb
│ │ ├── columns
│ │ │ └── create.turbo_stream.erb
│ │ ├── not_nows
│ │ │ └── create.turbo_stream.erb
│ │ └── streams
│ │ └── create.turbo_stream.erb
│ ├── left_positions
│ │ └── create.turbo_stream.erb
│ ├── right_positions
│ │ └── create.turbo_stream.erb
│ └── show
│ └── _add_card_button.html.erb
├── entropy
│ ├── _auto_close.html.erb
│ └── _knob.html.erb
├── event_summaries
│ └── _event_summary.html.erb
├── events
│ ├── _day.html.erb
│ ├── _empty_days.html.erb
│ ├── _event.html.erb
│ ├── day_timeline
│ │ ├── _column.html.erb
│ │ ├── _columns.html.erb
│ │ └── columns
│ │ ├── _events.html.erb
│ │ └── show.html.erb
│ ├── days
│ │ └── index.html.erb
│ ├── event
│ │ ├── _attachments.html.erb
│ │ ├── _layout.html.erb
│ │ ├── attachments
│ │ │ ├── _attachment.html.erb
│ │ │ ├── _remote_image.html.erb
│ │ │ └── _remote_video.html.erb
│ │ └── eventable
│ │ ├── _card.html.erb
│ │ ├── _card_published.html.erb
│ │ └── _comment.html.erb
│ ├── index
│ │ ├── _add_board_button.html.erb
│ │ ├── _add_card_button.html.erb
│ │ ├── _filter.html.erb
│ │ └── filter
│ │ ├── _board.html.erb
│ │ └── _user.html.erb
│ └── index.html.erb
├── filters
│ ├── _filter_toggle.html.erb
│ ├── _settings.html.erb
│ ├── create.turbo_stream.erb
│ ├── destroy.turbo_stream.erb
│ ├── settings
│ │ ├── _assignees.html.erb
│ │ ├── _boards.html.erb
│ │ ├── _cards.html.erb
│ │ ├── _closers.html.erb
│ │ ├── _controls.html.erb
│ │ ├── _creators.html.erb
│ │ ├── _indexed_by.html.erb
│ │ ├── _manage.html.erb
│ │ ├── _sorted_by.html.erb
│ │ ├── _tags.html.erb
│ │ ├── _terms.html.erb
│ │ ├── _time_window.html.erb
│ │ └── _toggle.html.erb
│ └── settings_refreshes
│ └── create.turbo_stream.erb
├── join_codes
│ ├── inactive.html.erb
│ └── new.html.erb
├── layouts
│ ├── _lightbox.html.erb
│ ├── action_text
│ │ └── contents
│ │ └── _content.html.erb
│ ├── application.html.erb
│ ├── mailer.html.erb
│ ├── mailer.text.erb
│ ├── public.html.erb
│ └── shared
│ ├── _flash.html.erb
│ ├── _head.html.erb
│ ├── _time_zone.html.erb
│ └── _user_css.html.erb
├── mailers
│ ├── export_mailer
│ │ ├── completed.html.erb
│ │ └── completed.text.erb
│ ├── identity_mailer
│ │ └── email_change_confirmation.text.erb
│ ├── magic_link_mailer
│ │ ├── sign_in_instructions.html.erb
│ │ └── sign_in_instructions.text.erb
│ └── notification
│ └── bundle_mailer
│ ├── _notification.html.erb
│ ├── _notification.text.erb
│ ├── event
│ │ ├── _body.html.erb
│ │ └── _body.text.erb
│ ├── mention
│ │ ├── _body.html.erb
│ │ └── _body.text.erb
│ ├── notification.html.erb
│ └── notification.text.erb
├── my
│ ├── _menu.html.erb
│ ├── menus
│ │ ├── _accounts.html.erb
│ │ ├── _boards.html.erb
│ │ ├── _custom_views.html.erb
│ │ ├── _jump.html.erb
│ │ ├── _people.html.erb
│ │ ├── _settings.html.erb
│ │ ├── _shortcuts.html.erb
│ │ ├── _tags.html.erb
│ │ └── show.html.erb
│ └── pins
│ ├── _pin.html.erb
│ ├── _tray.html.erb
│ └── index.html.erb
├── notifications
│ ├── _notification.html.erb
│ ├── _tray.html.erb
│ ├── index
│ │ ├── _notification.html.erb
│ │ ├── _read_notifications.html.erb
│ │ └── _unread_notifications.html.erb
│ ├── index.html.erb
│ ├── index.turbo_stream.erb
│ ├── notification
│ │ ├── _body.html.erb
│ │ ├── _header.html.erb
│ │ ├── event
│ │ │ └── _body.html.erb
│ │ └── mention
│ │ └── _body.html.erb
│ ├── readings
│ │ ├── create.turbo_stream.erb
│ │ └── destroy.turbo_stream.erb
│ ├── settings
│ │ ├── _board.html.erb
│ │ ├── _browser.html.erb
│ │ ├── _email.html.erb
│ │ ├── _install.html.erb
│ │ ├── _push_notifications.html.erb
│ │ ├── _system.html.erb
│ │ └── show.html.erb
│ ├── trays
│ │ └── show.html.erb
│ └── unsubscribes
│ ├── new.html.erb
│ └── show.html.erb
├── prompts
│ ├── boards
│ │ └── users
│ │ ├── _user.html.erb
│ │ └── index.html.erb
│ ├── cards
│ │ ├── _card.html.erb
│ │ └── index.html.erb
│ ├── commands
│ │ ├── _command.html.erb
│ │ └── index.html.erb
│ ├── tags
│ │ ├── _tag.html.erb
│ │ └── index.html.erb
│ └── users
│ └── index.html.erb
├── public
│ ├── _footer.html.erb
│ ├── boards
│ │ ├── card_previews
│ │ │ └── index.turbo_stream.erb
│ │ ├── columns
│ │ │ ├── _list.html.erb
│ │ │ ├── closeds
│ │ │ │ └── show.html.erb
│ │ │ ├── not_nows
│ │ │ │ └── show.html.erb
│ │ │ ├── show.html.erb
│ │ │ └── streams
│ │ │ └── show.html.erb
│ │ ├── show
│ │ │ ├── _closed.html.erb
│ │ │ ├── _column.html.erb
│ │ │ ├── _columns.html.erb
│ │ │ ├── _not_now.html.erb
│ │ │ └── _stream.html.erb
│ │ └── show.html.erb
│ └── cards
│ ├── show
│ │ ├── _content.html.erb
│ │ └── _steps.html.erb
│ └── show.html.erb
├── pwa
│ ├── manifest.json.erb
│ └── service_worker.js
├── searches
│ ├── _form.html.erb
│ ├── _result.html.erb
│ ├── _results.html.erb
│ └── show.html.erb
├── sessions
│ ├── _footer.html.erb
│ ├── magic_links
│ │ └── show.html.erb
│ ├── menus
│ │ └── show.html.erb
│ ├── new.html.erb
│ ├── starts
│ │ └── new.html.erb
│ └── transfers
│ └── show.html.erb
├── signups
│ ├── completions
│ │ └── new.html.erb
│ └── new.html.erb
├── tags
│ └── index.html.erb
├── user_mailer
│ └── email_change_confirmation.html.erb
├── users
│ ├── _activity_timeline.html.erb
│ ├── _attachable.html.erb
│ ├── _transfer.html.erb
│ ├── _user.json.jbuilder
│ ├── avatars
│ │ └── show.svg.erb
│ ├── edit.html.erb
│ ├── email_addresses
│ │ ├── confirmations
│ │ │ ├── invalid_token.html.erb
│ │ │ └── show.html.erb
│ │ ├── create.html.erb
│ │ └── new.html.erb
│ ├── events
│ │ └── show.html.erb
│ ├── joins
│ │ └── new.html.erb
│ ├── show.html.erb
│ └── verifications
│ └── new.html.erb
└── webhooks
├── _delivery.html.erb
├── _webhook.html.erb
├── edit.html.erb
├── event.html.erb
├── event.json.jbuilder
├── form
│ └── _actions.html.erb
├── index.html.erb
├── new.html.erb
└── show.html.erb
131 directories, 312 files
app/views/[resource_name]/xxx.html.erb
まあ、普通というか。素朴に Rails でビューを書いてるなって感じがします。うん、泥臭い。
少し気になったのは、ラベル名とか、プレイスホルダ—とか、ボタン名とか、直に書いて翻訳ファイル使わないんだなって。
<%= turbo_frame_tag @card, :edit do %>
<%# When entering edit mode, this turbo-stream updates the button area to show
"Save changes" instead of "Edit". Turbo processes this stream as part of the
frame response. %>
<%= turbo_stream.update dom_id(@card, :card_closure_toggle) do %>
<%= render "cards/container/save_button", card: @card %>
<% end %>
<%= form_with model: @card, id: dom_id(@card, :edit_form),
data: { controller: "autoresize form local-save", local_save_key_value: "card-#{@card.id}", action: "turbo:submit-end->local-save#submit" } do |form| %>
<h1 class="card__title flex align-start gap-half">
<%= form.label :title, class: "flex flex-column align-center autoresize__wrapper", data: { autoresize_target: "wrapper", autoresize_clone_value: "" } do %>
<%= form.text_area :title, class: "card-field__title autoresize__textarea input input--textarea full-width borderless txt-align-start hide-focus-ring hide-scrollbar",
required: true, autofocus: true, placeholder: "Name it…", rows: 1, dir: "auto", maxlength: 255,
data: { autoresize_target: "textarea", action: "input->autoresize#resize keydown.enter->form#submit:prevent keydown.ctrl+enter->form#submit:prevent keydown.meta+enter->form#submit:prevent keydown.esc->form#cancel focus->form#select" } %>
<% end %>
</h1>
<%= form.rich_textarea :description, class: "card__description rich-text-content",
placeholder: "Add some notes, context, pictures, or video about this…",
data: { local_save_target: "input", action: "lexxy:change->local-save#save turbo:morph-element->local-save#restoreContent keydown.ctrl+enter->form#submit:prevent keydown.meta+enter->form#submit:prevent keydown.esc->form#cancel:stop" } do %>
<%= general_prompts(@card.board) %>
<% end %>
<%= link_to "Close editor and discard changes", @card, data: { form_target: "cancel" }, hidden: true %>
<% end %>
<% end %>
翻訳ファイルはデフォルトのまま手つかずでした。
# Files in the config/locales directory are used for internationalization and
# are automatically loaded by Rails. If you want to use locales other than
# English, add the necessary files in this directory.
# (略)
en:
hello: "Hello world"
app/views/[resource_name]/xxx.json.jbuilder
Jbuilder の方も普通です。特に言うこと無いかな。
json.cache! [ card, card.column&.color ] do
json.(card, :id, :title, :status)
json.image_url card.image.presence && url_for(card.image)
json.golden card.golden?
json.last_active_at card.last_active_at.utc
json.created_at card.created_at.utc
json.url card_url(card)
json.board do
json.partial! "boards/board", locals: { board: card.board }
end
json.column do
if card.column
json.partial! "columns/column", column: card.column
else
nil
end
end
json.creator do
json.partial! "users/user", user: card.creator
end
end
app/views/[resource_name]/xxx.turbo_stream.rb
データの更新が伴うものは、Turbo Stream が多用されていました。
$ find app/views -type f | grep turbo_stream
app/views/columns/left_positions/create.turbo_stream.erb
app/views/columns/right_positions/create.turbo_stream.erb
app/views/columns/cards/drops/columns/create.turbo_stream.erb
app/views/columns/cards/drops/closures/create.turbo_stream.erb
app/views/columns/cards/drops/streams/create.turbo_stream.erb
app/views/columns/cards/drops/not_nows/create.turbo_stream.erb
app/views/public/boards/card_previews/index.turbo_stream.erb
app/views/notifications/readings/create.turbo_stream.erb
app/views/notifications/readings/destroy.turbo_stream.erb
app/views/notifications/index.turbo_stream.erb
app/views/boards/publications/create.turbo_stream.erb
app/views/boards/publications/destroy.turbo_stream.erb
app/views/boards/columns/create.turbo_stream.erb
app/views/boards/columns/update.turbo_stream.erb
app/views/boards/columns/destroy.turbo_stream.erb
app/views/boards/entropies/update.turbo_stream.erb
app/views/filters/create.turbo_stream.erb
app/views/filters/settings_refreshes/create.turbo_stream.erb
app/views/filters/destroy.turbo_stream.erb
app/views/cards/update.turbo_stream.erb
app/views/cards/readings/create.turbo_stream.erb
app/views/cards/previews/index.turbo_stream.erb
app/views/cards/watches/create.turbo_stream.erb
app/views/cards/watches/_refresh.turbo_stream.erb
app/views/cards/watches/destroy.turbo_stream.erb
app/views/cards/comments/create.turbo_stream.erb
app/views/cards/comments/update.turbo_stream.erb
app/views/cards/comments/reactions/create.turbo_stream.erb
app/views/cards/comments/reactions/destroy.turbo_stream.erb
app/views/cards/comments/destroy.turbo_stream.erb
app/views/cards/taggings/create.turbo_stream.erb
app/views/cards/steps/create.turbo_stream.erb
app/views/cards/steps/update.turbo_stream.erb
app/views/cards/steps/destroy.turbo_stream.erb
app/views/cards/assignments/create.turbo_stream.erb
<%= turbo_stream.replace dom_id(@card, :card_container), partial: "cards/container", method: :morph, locals: { card: @card.reload } %>
<%= turbo_stream.update dom_id(@card, :edit) do %>
<%= render "cards/container/content_display", card: @card %>
<% end %>
<%= turbo_stream.replace dom_id(@card, :card_closure_toggle) do %>
<%= render "cards/container/closure", card: @card %>
<% end %>
dom_id には、第2引数まで指定してプレフィックスをつけて細かく turbo_stream.replace されてました。
irb> helper.dom_id(Card.first, :card_container)
=> "card_container_card_03f6ofejepfetx4d591gzd9cf"
app/helpers
次は、ヘルパーを見ていきます。
何があるか確認してみます。
$ tree app/helpers/
app/helpers/
├── accesses_helper.rb
├── application_helper.rb
├── avatars_helper.rb
├── boards_helper.rb
├── cards_helper.rb
├── clipboard_helper.rb
├── columns_helper.rb
├── comments_helper.rb
├── emoji_helper.rb
├── entropy_helper.rb
├── events_helper.rb
├── excerpt_helper.rb
├── filters_helper.rb
├── forms_helper.rb
├── hotkeys_helper.rb
├── html_helper.rb
├── login_helper.rb
├── messages_helper.rb
├── my
│ └── menu_helper.rb
├── notifications_helper.rb
├── pagination_helper.rb
├── qr_codes_helper.rb
├── rich_text_helper.rb
├── tenanting_helper.rb
├── time_helper.rb
├── users_helper.rb
└── webhooks_helper.rb
2 directories, 27 files
私は Rails を使っていて、モデル名に紐づくヘルパーってあまり使わないので、各ファイルがモデル名に紐づいてるのか興味があり、ちょっと確認してみます。
大雑把に、モデル名に紐づいてるのとそうでないのと半々ぐらいでした。
irb> models = Dir['app/models/**/*.rb'].map{|f| f[/(\w+)\.rb/, 1].pluralize }
irb> Dir['app/helpers/**/*.rb'].group_by{|f| f[/(\w+)_helper\.rb/, 1].in? models }
=>
{true =>
["app/helpers/accesses_helper.rb",
"app/helpers/avatars_helper.rb",
"app/helpers/boards_helper.rb",
"app/helpers/cards_helper.rb",
"app/helpers/columns_helper.rb",
"app/helpers/comments_helper.rb",
"app/helpers/events_helper.rb",
"app/helpers/filters_helper.rb",
"app/helpers/notifications_helper.rb",
"app/helpers/users_helper.rb",
"app/helpers/webhooks_helper.rb"],
false =>
["app/helpers/application_helper.rb",
"app/helpers/clipboard_helper.rb",
"app/helpers/emoji_helper.rb",
"app/helpers/entropy_helper.rb",
"app/helpers/excerpt_helper.rb",
"app/helpers/forms_helper.rb",
"app/helpers/hotkeys_helper.rb",
"app/helpers/html_helper.rb",
"app/helpers/login_helper.rb",
"app/helpers/messages_helper.rb",
"app/helpers/my/menu_helper.rb",
"app/helpers/pagination_helper.rb",
"app/helpers/qr_codes_helper.rb",
"app/helpers/rich_text_helper.rb",
"app/helpers/tenanting_helper.rb",
"app/helpers/time_helper.rb"]}
app/helpers/[model_name]_helper.rb
The Rails Doctrine で、一つの名前空間という大鍋に放り込まれた昔ながらの PHP のスープのようだと DHH 自ら形容していたヘルパー。
とりあえず接頭辞をつけるなどで、名前は意識してる?のかな。
module CardsHelper
def card_article_tag(card, id: dom_id(card, :article), data: {}, **options, &block)
classes = [
options.delete(:class),
("golden-effect" if card.golden?),
("card--postponed" if card.postponed?),
("card--active" if card.active?)
].compact.join(" ")
data[:drag_and_drop_top] = true if card.golden? && !card.closed? && !card.postponed?
tag.article \
id: id,
style: "--card-color: #{card.color}; view-transition-name: #{id}",
class: classes,
data: data,
**options,
&block
end
def card_title_tag(card)
title = [
card.title,
"added by #{card.creator.name}",
"in #{card.board.name}"
]
title << "assigned to #{card.assignees.map(&:name).to_sentence}" if card.assignees.any?
title.join(" ")
end
def card_drafted_or_added(card)
card.drafted? ? "Drafted" : "Added"
end
def card_social_tags(card)
tag.meta(property: "og:title", content: "#{card.title} | #{card.board.name}") +
tag.meta(property: "og:description", content: format_excerpt(card&.description, length: 200)) +
tag.meta(property: "og:image", content: card.image.attached? ? "#{request.base_url}#{url_for(card.image)}" : "#{request.base_url}/opengraph.png") +
tag.meta(property: "og:url", content: card_url(card))
end
def button_to_remove_card_image(card)
button_to(card_image_path(card), method: :delete, class: "btn", data: { controller: "tooltip", action: "dialog#close" }) do
icon_tag("trash") + tag.span("Remove background image", class: "for-screen-reader")
end
end
end
app/helpers/xxx_helper.rb
module TimeHelper
def local_datetime_tag(datetime, style: :time, **attributes)
# Render empty space to ensure it takes height until the local time is loaded via JS
tag.time " ".html_safe, **attributes, datetime: datetime.to_i, data: { local_time_target: style, action: "turbo:morph-element->local-time#refreshTarget" }
end
end
include XxxHelper
ヘルパーをビュー以外の用途で使っている箇所を確認してみましたが、以下2箇所だけでした。
ExcerptHelper
文字列処理のヘルパーがモデルで使われていました。
module ExcerptHelper
def format_excerpt(content, length: 200)
return "" if content.blank?
text = content.respond_to?(:to_plain_text) ? content.to_plain_text : content.to_s
text = text.gsub(/^>\s*(.*)$/m, '> \1')
text = text.gsub(/^\s*[-+]\s*(.*)$/m, '• \1')
text = text.gsub(/^\d+\.\s*(.*)$/m) { |m| m }
text = text.gsub(/\s+/, " ").strip
text.truncate(length)
end
end
class NotificationPusher
include Rails.application.routes.url_helpers
include ExcerptHelper
# 略
def build_mention_payload
mention = notification.source
card = mention.card
{
title: "#{mention.mentioner.first_name} mentioned you",
body: format_excerpt(mention.source.mentionable_content, length: 200),
path: card_path(card)
}
end
# 略
LoginHelper
ログイン周りのヘルパーがコントローラから呼ばれていました。
module LoginHelper
def login_url
# Use main_app because this helper may be invoked from an engine controller
# that inherits from AdminController.
main_app.new_session_path(script_name: nil)
end
def logout_url
main_app.new_session_path
end
def redirect_to_login_url
redirect_to login_url, allow_other_host: true
end
def redirect_to_logout_url
redirect_to logout_url, allow_other_host: true
end
end
module Authentication
extend ActiveSupport::Concern
included do
before_action :require_account # Checking and setting account must happen first
before_action :require_authentication
after_action :ensure_development_magic_link_not_leaked
helper_method :authenticated?
etag { Current.session.id if authenticated? }
include LoginHelper
end
# 略
まとめ
もうちょっと見たい気もしましたが、疲れました。
長々と、うまくまとめれた気があまりしませんが、誰かの参考になれば幸いです。
以上です。
Discussion