Skip to content

Instantly share code, notes, and snippets.

@Papillard
Created July 17, 2013 14:26
Show Gist options
  • Select an option

  • Save Papillard/6021024 to your computer and use it in GitHub Desktop.

Select an option

Save Papillard/6021024 to your computer and use it in GitHub Desktop.
Use callbacks to make your controller concise
# 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
# 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