Last active
August 29, 2015 14:06
-
-
Save rummelonp/2804e70f46df4516a2ab to your computer and use it in GitHub Desktop.
Rails で Form クラス的なやつ
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 ApplicationForm | |
include ActiveModel::Model | |
def submit(params = {}) | |
params.each do |key, value| | |
self.public_send("#{key}=", value) | |
end | |
self | |
end | |
def save | |
raise NotImplementedError | |
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 NyanWanForm < ApplicationForm | |
## Attributes | |
attr_reader :nyan | |
# Define some attributes | |
## Validations | |
# Define some validations | |
def initialize(nyan) | |
@nyan = nyan | |
end | |
def save | |
return false unless valid? | |
nyan.transaction do | |
# do something | |
end | |
true | |
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 NyansController < ApplicationController | |
def wans_new | |
@form = NyanWanForm.new(@nyan) | |
end | |
def wans_create | |
@form = NyanWanForm.new(@nyan).submit(nyan_wan_params) | |
if @form.save | |
# do something | |
else | |
render :wans_new | |
end | |
end | |
private | |
def nyan_wan_params | |
params.require(:nyan_wan_form).permit( | |
# Some attributes | |
) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment