Skip to content

Instantly share code, notes, and snippets.

@TalkativeTree
Created January 28, 2014 04:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TalkativeTree/8662395 to your computer and use it in GitHub Desktop.
Save TalkativeTree/8662395 to your computer and use it in GitHub Desktop.
class PostsController
def new
@post = Post.new
end
def create
service = post_service.new
service.delegate = self
service.create_new_post(params[:post])
end
# PostServiceProtocol begins
def new_post_created_successfully(post)
redirect_to posts_path, :notice => "Post created succesfully!"
end
def new_post_not_created_because_of(errors)
render :new
end
# PostServiceProtocol ends
private
# I don't like this way
def post_service
eval("
class PostService
attr_writer :delegate
def create_new_post(params)
post = Post.new(params)
if post.save
self.delegate.new_post_created_successfully(post)
else
self.delegate.new_post_not_created_because_of(post.errors)
end
end
protected
def delegate
@delegate ||= NullPostServiceDelegate.new
end
end
class NullPostServiceDelegate
def new_post_created_successfully(post)
# no-op
end
def new_post_not_created_because_of(errors)
# no-op
end
end
")
PostService
end
# I actually like this way.
def post_service_two
require_relative 'public_classes'
PostService
end
end
puts "PostsController.constants: #{PostsController.constants}"
puts "PostService: #{PostService}"
class PostsController
def new
@post = Post.new
end
def create
service = post_service.new
service.delegate = self
service.create_new_post(params[:post])
end
# PostServiceProtocol begins
def new_post_created_successfully(post)
redirect_to posts_path, :notice => "Post created succesfully!"
end
def new_post_not_created_because_of(errors)
render :new
end
# PostServiceProtocol ends
private
# I don't like this way
def post_service
eval("
class PostService
attr_writer :delegate
def create_new_post(params)
post = Post.new(params)
if post.save
self.delegate.new_post_created_successfully(post)
else
self.delegate.new_post_not_created_because_of(post.errors)
end
end
protected
def delegate
@delegate ||= NullPostServiceDelegate.new
end
end
class NullPostServiceDelegate
def new_post_created_successfully(post)
# no-op
end
def new_post_not_created_because_of(errors)
# no-op
end
end
")
PostService
end
# I actually like this way.
def post_service_two
require_relative 'public_classes'
PostService
end
end
puts "PostsController.constants: #{PostsController.constants}"
puts "PostService: #{PostService}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment