Saturday, December 13, 2008

How to access session, cookies, params, request in Model

You’re completely/totally/fucking wrong if you want to access sessions, params, cookies, etc. in your Models.

You can’t get more wrong than this in rails world probably. But some people just don’t get it. So if you must, this is how you can do it
Add this code at the bottom of your application.rb

class ApplicationController
# Your existing stuff
around_filter :you_dont_have_bloody_clue

protected

def you_dont_have_bloody_clue
klasses = [ActiveRecord::Base, ActiveRecord::Base.class]
methods = ["session", "cookies", "params", "request"]

methods.each do |shenanigan|
oops = instance_variable_get(:"@_#{shenanigan}")
klasses.each{ |klass| klass.send(:define_method, shenanigan, proc { oops }) }
end

yield

methods.each { |shenanigan| klasses.each{ |klass| klass.send :remove_method, shenanigan } }

end

Again, do it if you wish, just don’t ask anyone how to do it ever again!

http://m.onkey.org/2007/10/17/how-to-access-session-cookies-params-request-in-model

No comments: