Notes posted by rubymaverick
RSS feedHow I use Optimistic Locking
I have used Optimistic locking often, but usually I only need it in one or two places in the codebase, not everywhere an object is saved whose model has a lock_version column. So what I usually end up doing is using a little module I wrote called OptimisticallyLockable (awesome name right?). Here it is:
module OptimisticallyLockable def self.included(receiver) receiver.lock_optimistically = false receiver.class_eval do def self.with_optimistic_locking original_lock = self.lock_optimistically self.lock_optimistically = true begin yield ensure self.lock_optimistically = original_lock end end end end end
When included in a model that has a lock_version column it will turn off optimistic locking. Then when you want to actually use optimistic locking you can just use the with_optimistic_locking method like this:
class Blog include OptimisticallyLockable def do_something_destructive! self.class.with_optimistic_locking do # do something important here end end end
Rails defined Mime Types
Here are all the default Rails Mime Types:
"*/*" => :all "text/plain" => :text "text/html" => :html "application/xhtml+xml" => :html "text/javascript" => :js "application/javascript" => :js "application/x-javascript" => :js "text/calendar" => :ics "text/csv" => :csv "application/xml" => :xml "text/xml" => :xml "application/x-xml" => :xml "text/yaml" => :yaml "application/x-yaml" => :yaml "application/rss+xml" => :rss "application/atom+xml" => :atom "application/json" => :json "text/x-json" => :json
Default Mime Types
This module sets up all the default mime-types. Here they are:
"*/*" => :all "text/plain" => :text "text/html" => :html "application/xhtml+xml" => :html "text/javascript" => :js "application/javascript" => :js "application/x-javascript" => :js "text/calendar" => :ics "text/csv" => :csv "application/xml" => :xml "text/xml" => :xml "application/x-xml" => :xml "text/yaml" => :yaml "application/x-yaml" => :yaml "application/rss+xml" => :rss "application/atom+xml" => :atom "application/json" => :json "text/x-json" => :json
How to test different responses in controller tests/specs
When you want to write a controller test or spec (rspec) to test out a different response type other than html, just set the HTTP_ACCEPTS header like so before the request:
@request.env['HTTP_ACCEPT'] = "application/rss" post :create, :blog => {}
Custom MIME Type
After you register a custom Mime::Type like stated above, you can do:
respond_to do |format| # .jpg corresponds to the second argument passed to #register # Mime::Type.register "image/jpg", :jpg format.jpg { ...do something here... } end