Beast Source Code Snippet
April 18th, 2007I downloaded and browsed the source code for the Beast forum today. Because it’s REST’ful, open source, and developed by Rick Olson, I recommend any Rails developer to look at it. What makes it even better is that a goal of Beast is to “stay around 500 lines”, meaning the app doesn’t take much time to figure out and can be studied leisurely.
Anything you define in YourController#rescue_action will be run when an error is raised, so check out what I found in Beast:
def rescue_action(exception)
exception.is_a?(ActiveRecord::RecordInvalid) ? render_invalid_record(exception.record) : super
end
def render_invalid_record(record)
render :action => (record.new_record? ? ‘new’ : ‘edit’)
end
As you can see, now any errors that are invalid AR objects will call a special method. This method render’s new or edit depending on whether the record exists yet or not.
So…rather than doing this in our controllers:
def create
@record = Record.new(params[:record])
if @record.save
flash[:notice] = ‘Saved successfully’
redirect_to :action => ‘index’
else
render :action => ‘new’
end
end
We simply do this:
def create
@record = Record.new(params[:record])
@record.save! and flash[:notice]=(’Saved successfully’) and redirect_to(:action => ‘index’)
end
The magic is in the save! method, as the “bang” raises errors instead of returning false when validation fails, not bad!
On another note, I’ve been spending a lot of my time recently on reading books about and developing a social site… As you know, my ambition to blog a lot since the creation of larrytheliquid.com has quickly diminished. I’m making this app to change that for myself and all bloggers… but that’s enough for now =)
