Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails 5, how access cookies method in a model or helper?

How does one access cookies inside a Rails model or helper?

Trying to dry up some controller methods, I am trying to move multiple controller calls to cookies() into application_helper.rb and/or a model.

What doesn't work in application_helper.rb:

cookies[:foo]
ActionDispatch::Cookies.cookies[:foo]
ActionController.cookies[:foo]
ActionDispatch::Cookies::ChainedCookieJars.cookie[:foo]

All of which result in undefined method 'cookies'

Note: Well-meaning answers that simply regurgitate MVC dogma are mis-placed here... I've architected long enough (decades) to know when coloring outside the MVC lines (if possible) is the better route. But the precise syntax eludes me even after digging through Rails source. This question is prompted by a somewhat complex situation related to, among other things, inconsistent browser handling of cookies in cross-domain, ajax environment that sometimes includes local files (for which Chrome declines to manage cookies).

like image 884
jpw Avatar asked Sep 11 '25 17:09

jpw


1 Answers

It's not a good idea :) Models are classes, and they shouldn't be aware of what is happening on a web level, and that's why cookies method is implemented in ActionController, but there's no such implementation in ActionModel or ActionHelper. If you need a cookie value in a model, pass a value from a controller then. This is how it should be done.

like image 64
Vasili Avatar answered Sep 13 '25 08:09

Vasili