Skip to content

Instantly share code, notes, and snippets.

@rummelonp
Created March 24, 2017 09:40
Show Gist options
  • Save rummelonp/cca54dfc6c751de7ee370623c18e18ee to your computer and use it in GitHub Desktop.
Save rummelonp/cca54dfc6c751de7ee370623c18e18ee to your computer and use it in GitHub Desktop.
application_service.rb
class ApplicationService
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 Article < ApplicationRecord
# どんな状況でも絶対に満たしたい条件のバリデーションを書く
validates :title, presence: true
validates :body, length: {maximum: 1024}
end
class CreateDraftArticleService < ApplicationService
attr_accessor :title, :body
# 下書き時は body が空でも良い
validates :title, presence: true
validates :body, presence: false, length: {maximum: 1024}
def save
Article.create(title: title, body: body)
end
end
class PublishArticleService < ApplicationService
attr_accessor :title, :body
# 記事公開時は body 必須
validates :title, presence: true
validates :body, presence: true, length: {maximum: 1024}
def initialize(article)
@article = article
end
def save
@article.update(title: title, body: body)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment