Skip to content

Instantly share code, notes, and snippets.

@rummelonp
Last active August 29, 2015 14:06
Show Gist options
  • Save rummelonp/2804e70f46df4516a2ab to your computer and use it in GitHub Desktop.
Save rummelonp/2804e70f46df4516a2ab to your computer and use it in GitHub Desktop.
Rails で Form クラス的なやつ
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
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
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