0

Situation: I want to validate some user permissions immediately before saving a document, so the obvious solution I came up with was to make a DocumentObserver and modify the before_save method to do the check. However, the problem with doing this is that models can't easily (and shouldn't) access current_user, which would be necessary to perform the check. I understand it is possible to hack around this by using Thread, but I'd rather follow standard practices if possible. Is there a way to make this happen or a better way to achieve the same result? The observer just seems like such an intuitive and simple solution, it'd be a shame not to use it.

Considerations: My problem is similar to this one, but I was hoping to get a more concrete answer or suggestion. For reference, here is the current_user workaround

Revision: Further complication - the controller is in a third party gem that I cannot modify, meaning I can't simply pass in the current_user to the model. this complication may force me to patch over some of the third party's methods or something, unless there's some other clever way to get this to work...

Community
  • 1
  • 1
Chance R.
  • 68
  • 8
  • 1
    Even if you can't alter the source code of you controller, you can still inject some filters to the controllers/actions, or use `alias_method_chain` to alter the behavior of you actions – Dean Winchester Jul 09 '13 at 14:28

1 Answers1

0

The model is to provide API. You don't need to access helper method in model, which is also a very bad practice.

It's simple to solve your problem. Just provide an user instance as method argument.

# model
def my_model_method(user)
  # then use this user
end

# controller/view
@int.my_model_method(current_user)
Billy Chan
  • 24,625
  • 4
  • 52
  • 68
  • Hmm, the problem is that the controller is in a third party gem so I can't modify it. I probably should have mentioned that in the question...revised it to reflect that important point. – Chance R. Jul 09 '13 at 14:07
  • If you have to do this, that means you are trying to access session in model. http://m.onkey.org/how-to-access-session-cookies-params-request-in-model – Dean Winchester Jul 09 '13 at 14:15
  • @ChanceR., third party gem doesn't matter. You can write an method in ApplicationController to overwrite the specific method, or with a bit more effort to write a controller class to inherit and overwrite it. – Billy Chan Jul 09 '13 at 16:20
  • @DeanWinchester, there must be a way around it like I commented above, or others if you take a bit time to think. I would never access session stuff in model. – Billy Chan Jul 09 '13 at 16:21
  • Thanks for both y'alls input, I ended up essentially doing what @BillyChan suggested, just overwrote the gem controllers & passed it in. Yeah, it's bad style, and yeah it's pretty awkward, but under the conditions I was handed I didn't have much choice. – Chance R. Jul 09 '13 at 16:41