Last active
January 26, 2025 07:08
-
-
Save wtnabe/7659c69522c871dfe4effcb0bea3956d to your computer and use it in GitHub Desktop.
dry-operation + dry-monads + ActiveModelほかいくつかの処理を交えていい具合にViewに返す試み
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<% unless errors.empty? %> | |
エラーあります | |
<ul> | |
<% errors.each do |error| %> | |
<% # ActiveModel::ErrorsとDry::Schema::Message的なエラーをいい具合に扱う %> | |
<li><%= error.try(:attribute) || error.try(:path) %> : <%= error.try(:type) || error.try(:text) %></li> | |
<% end %> | |
</ul> | |
<% end %> | |
<% unless data.empty? %> | |
<a href="<%= data[:url] %>">>> next</a> | |
<% end %> | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "sinatra" | |
get "/" do | |
erb :new, locals: {anti_csrf_token: env["rack.session"][:csrf]} | |
end | |
post "/confirm" do | |
result = GenerateMagiclink.new.call(params["entry"]) | |
erb: :confirm, locals: { | |
data: result.success? ? {url: result.value!} : {}, | |
errors: result.failure? ? result.failure.errors: [] | |
} | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "dry/operation" | |
require_relative "../models/email_form" | |
require_relative "../models/email_reachable" | |
require_relative "../models/magic_link" | |
class GenerateMagiclink < Dry::Operation | |
# | |
# 各stepに与えるメソッドはDry::Monads::Resultを返すこと | |
# see https://dry-rb.org/gems/dry-monads/main/result/ | |
# Operationの中ではSucess(), Failure()はinclude済みだが、外部のModelを利用する場合は注意が必要 | |
# call全体がDry::Monads::Resultを返すので最終行はstepがないとResultがネストする可能性アリ | |
# | |
def call(user_input) | |
email = step validate_input(user_input) | |
step EmailReachable.new(email).reachable? | |
step MagicLink.new(email).generate | |
end | |
def validate_input(params) | |
form = EmailForm.new(params) | |
form.valid? ? Success(form.email) : Failure(form) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment