Created
July 17, 2013 14:26
-
-
Save Papillard/6021024 to your computer and use it in GitHub Desktop.
Use callbacks to make your controller concise
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
| # More readable controller where "hot topic" logic delegate to model callback | |
| class TopicsController < ApplicationController | |
| def create | |
| @topic = Topic.new(params[:topic]) | |
| if @topic.save | |
| redirect_to @topic, :notice => 'Successfully created a Tweet' | |
| else | |
| render :new | |
| end | |
| end | |
| end | |
| class Topic < ActiveRecord::Base | |
| HOT_TOPIC_MENTIONS = 5000 | |
| before_create :set_hot_topic, if: :hot_topic? | |
| protected | |
| def set_hot_topic | |
| self.hot_topic = true | |
| end | |
| def hot_topic? | |
| mentions > HOT_TOPIC_MENTIONS | |
| end | |
| end |
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
| # Poor version without callbacks : all "hot topic" logic in the controller.. | |
| class TopicsController < ApplicationController | |
| def create | |
| @topic = Topic.new(params[:topic]) | |
| @topic.hot_topic = true if @topic.mentions > Topic::HOT_TOPIC_MENTIONS | |
| if @topic.save | |
| redirect_to @topic, :notice => 'Successfully created a Tweet' | |
| else | |
| render :new | |
| end | |
| end | |
| end | |
| class Topic < ActiveRecord::Base | |
| HOT_TOPIC_MENTIONS = 5000 | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment