Skip to content

Instantly share code, notes, and snippets.

@smellman
Last active December 17, 2015 06:49
Show Gist options
  • Save smellman/5567966 to your computer and use it in GitHub Desktop.
Save smellman/5567966 to your computer and use it in GitHub Desktop.
http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/ Extra Decoratorで、Decoratorの連鎖をしてみたサンプル
require "delegate"
require "optparse"
# Socail Logic
class Facebook
def self.post(title, user)
p "post to facebook, title: #{title}, user: #{user}"
end
end
class Twitter
def self.post(title, user)
p "post to twitter, title: #{title}, user: #{user}"
end
end
class Plus
def self.post(title)
p "post to plus, title: #{title}"
end
end
# Model
class Comment
attr :title
attr :author
def initialize(title, author)
@title = title
@author = author
end
def save
p "save to comment model, title: #{title}, author: #{author}"
end
end
# Decorator
class FacebookCommentNotifier < SimpleDelegator
def initialize(comment)
@comment = comment
super
end
def save
@comment.save && post_to_wall
end
private
def post_to_wall
Facebook.post(@comment.title, @comment.author)
end
end
class TwitterCommentNotifier < SimpleDelegator
def initialize(comment)
@comment = comment
super
end
def save
@comment.save && post_to_wall
end
private
def post_to_wall
Twitter.post(@comment.title, @comment.author)
end
end
class PlusCommentNotifier < SimpleDelegator
def initialize(comment)
@comment = comment
super
end
def save
@comment.save && post_to_wall
end
private
def post_to_wall
Plus.post(@comment.title)
end
end
# main
if __FILE__ == $0
title = ""
user = ""
params = Hash.new
opt = OptionParser.new
opt.on('-t', '--title=VAL') {|v| title = v}
opt.on('-u', '--user=VAL') {|v| user = v}
opt.on('--[no-]fb') {|v| params[:fb] = v}
opt.on('--[no-]tw') {|v| params[:tw] = v}
opt.on('--[no-]pl') {|v| params[:pl] = v}
opt.parse!(ARGV)
@comment = Comment.new(title, user)
if params[:fb]
@comment = FacebookCommentNotifier.new(@comment)
end
if params[:tw]
@comment = TwitterCommentNotifier.new(@comment)
end
if params[:pl]
@comment = PlusCommentNotifier.new(@comment)
end
if @comment.save
p "Your comment was posted."
else
p "Your comment can't post"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment