unscoped

unscoped is used by a number of pesky rails methods1.

This would be fine, except that occasionally, when doing sneaky things2 in Rails you want your default_scope to apply almost all the time.

Thus:

def self.unscoped(original = false)
  if original
    super()
  elsif block_given?
    super(&nil).default_scope.scoping { yield }
  else
    super().default_scope
  end
end

def self.really_unscoped
  unscoped(true)
end

That’s all for today.

(wow it’s like I’m writing an actual programming blog, with a post about some obscure hack that a total of 3 people will ever need).

  1. “Which methods?” you ask. update_columns and reload at least.

  2. “What kind of sneaky things?” you ask. Well, if you use non-unique ids and determine out which record with that id you want in the defualt_scope it becomes kind of necessary.3

  3. “Ok… Wait… What? Why would you do that?” you ask, quite reasonably. I run away.