Skip to content

Instantly share code, notes, and snippets.

@Taishikun0721
Last active January 19, 2021 14:40
Show Gist options
  • Save Taishikun0721/d73b10efcf0d131ed152e5d996709ef9 to your computer and use it in GitHub Desktop.
Save Taishikun0721/d73b10efcf0d131ed152e5d996709ef9 to your computer and use it in GitHub Desktop.
Railsもどき

MVCを意識して生RubyでRailsっぽく複数画像投稿処理を書いてみた

題材

フォームオブジェクトを使用して複数枚画像を投稿する処理をシンプルなRubyで 表現した場合どうなるのかなとイメトレとしてやってみた。

各ファイル説明

view.rb


ユーザーがパラメーターを記入する画面 今回ならformがある画面になる。

posts_controller.rb


名前の通りコントローラーで、PostFormクラスのインスタンスを初期化している

post_form.rb


フォームオブジェクトのクラス。ここに複数画像登録用のバリデーションとかロジックが書かれている。

post.rbとimage.rb


モデルの役割、RailsでいうDBのカラムを定義している.

仕様


今回ActiveRecordを使っていないのでsave!メソッドの代わりに。putsメソッドを使用しています。その為リダイレクトして登録した内容を出すように仮定した場合、コンソールがリダイレクト先のViewになります

class Image
attr_accessor :image
def initialize(image)
@image = image
end
end
class Post
attr_accessor :title
def initialize(title)
@title = title
end
end
require_relative './post'
require_relative './image'
class PostForm
attr_accessor :title, :images
def initialize(title, images)
@title = title
@images = images
end
# 本当ならこのあたりにバリデーションとか書く
# puts がsave!の代わりになっているイメージ
# ここはトランザクションとかで囲むべきかな。。めっちゃsave!(puts)してるし。
def save
post_instance = Post.new(title)
puts post_instance.title
images.each do |image|
return unless image
image_instance = Image.new(image)
puts "これはイメージ#{image_instance.image}です。"
end
end
end
require_relative './post_form'
# これがフォームオブジェクト用クラスののインスタンスが初期化されている
def create(title, images)
post_form = PostForm.new(title, images)
post_form.save
end
require_relative './posts_controller'
# viewでform_withかなにかでパラメーターが送られてくるイメージ
create('test', [1, 2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment