On Github y-yagi / introduction_to_trailblazer
Ginzarb 第35回 / @y-yagi
class CommentsController < ApplicationController
def new
form Comment::Update
end
def create
run Comment::Update do |op|
return redirect_to comments_path(op.model)
end
render :new
end
end
class Comment < ActiveRecord::Base
has_many :users
belongs_to :thing
scope :recent, -> { limit(10) }
end
class Comment::Create < Trailblazer::Operation
contract do
property :body
validates :body, length: {maximum: 160}
end
def process(params)
if validate(params)
...
else
...
end
end
end
contract do
property :body
validates :body, length: {maximum: 160}
property :author do
property :email
validates :email, email: true
end
end
class Comment::Create < Trailblazer::Operation
callback :after_save do
# this is a Disposable::Callback::Group class.
end
end
class AfterSave < Disposable::Callback::Group on_change :notify! end
class Thing::Policy
def initialize(user, thing)
@user, @thing = user, thing
end
def create?
admin?
end
def admin?
@user.admin == true
end
# ..
end
class Comment::Cell < Cell::ViewModel
property :body
property :author
def show
render
end
private
def author_link
link_to "#{author.email}", author
end
end
<div class="comment"> <%= body %> By <%= author_link %> </div>
<h1>Comments for <%= @thing.name %></h1>
This was created <%= @thing.created_at %>
<%= concept("comment/cell",
collection: @thing.comments) %>
class SongRepresenter < Representable::Decorator include Representable::JSON property :title property :track end
SongRepresenter.new(song).to_json
#=> {"title":"Fallout","track":1}
などもある
gemgem-trbrb: The Trailblazer book's example app.にTrailblazer本用のサンプルアプリがあるので、詳細はそちらを参照。