Created
July 2, 2012 18:50
-
-
Save nicholasjhenry/3034867 to your computer and use it in GitHub Desktop.
More ideas on SRP with Rails and ActiveRecord
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module MyApp | |
| BusinessException = Class.new(StandardError) | |
| class Post | |
| attr_reader :record | |
| def initialize(args) | |
| @record = args[:record] | |
| and | |
| def comment(record) | |
| create_comment(record) | |
| end | |
| def create_comment(record) | |
| Comment.new(record: record, post: self) | |
| end | |
| def add_comment? | |
| raise BusinessException.new("No more than 10 comments") if record.comments == 10 | |
| end | |
| end | |
| class Comment | |
| attr_reader :record, :post | |
| def initialize(args) | |
| @record = args[:record] | |
| add_post(args[:post]) | |
| and | |
| def add_post(post) | |
| self.add_post?(post) | |
| post.add_comment?(self) | |
| end | |
| def self.add_post?(post) | |
| true | |
| end | |
| end | |
| # controller.rb | |
| def create | |
| @post = Post.find(params[:post_id]) | |
| @comment = @post.build_comment(params[:comment]) | |
| comment(@post, @comment) | |
| if @comment.save | |
| redirect_to @post | |
| else | |
| render :new | |
| end | |
| end | |
| def comment(post_record, comment_record) | |
| post = MyApp::Post.new(post_record) | |
| post.comment(comment_record) | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment