Created
January 28, 2020 13:35
-
-
Save maicher/9ebc478964aacffad380e62d82427256 to your computer and use it in GitHub Desktop.
Inputs with dry-validation v2
This file contains hidden or 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
def new | |
# initialize a hash from | |
@inputs = Form.new( | |
user_name: '', | |
some_field: some_object.default_some_field, | |
something: { | |
a: '', | |
b: 'some default value' | |
} | |
) | |
end | |
def create | |
create_user = CreateUserTransaction.new | |
create_user.call(params) do |result| | |
result.success do |outcome| | |
#.. | |
redirect... | |
end | |
result.failure do |outcome| | |
flash.now[:error] = outcome[:description] | |
@inputs = Form.new(outcome[:validation]) | |
render :edit | |
end | |
end |
This file contains hidden or 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
class Form | |
def initialize(inputs) | |
@inputs = inputs | |
end | |
def value(*keys) | |
inputs.dig(*keys) | |
end | |
def error(*keys) | |
errors.dig(*keys).first | |
end | |
def errors | |
@errors ||= build_errors | |
end | |
private | |
attr_reader :inputs | |
def build_errors | |
return {} unless inputs.respond_to?(:errors) | |
inputs.errors.to_h | |
end | |
end |
This file contains hidden or 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
<input name="user_name" type="text" value="<%= inputs.value(:user_name) %>" /> | |
<% if form.error(:user_name) %> | |
<span class="text-danger"><%= form.error(:user_name) %></span> | |
<% end %> | |
<h3>Something</h3> | |
<input name="user_name[something][a]" type="text" value="<%= inputs.value(:something, :a) %>" /> | |
<% if form.error(:something, :a) %> | |
<span class="text-danger"><%= form.error(:somethind, :a) %></span> | |
<% end %> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment