0

I am working on a feature to limit the number of pages a user can access in a day. My plan is to create a class variable in the ApplicationController which is instantiated on startup. One of the features I want though is for this value to be changed by an administrator without having to worry about changing the config file, hence the class variable.

How can I have rails call a function in the application controller when rails starts up?

5
  • You could just have a database column in your User model called User.total_pages and just update that column everytime you visit a page. You'd have to check whether the condition was satisifed everytime you visit a page.
    – the12
    Jul 24, 2017 at 19:48
  • @the12 this would not work since the column would not track when the user has accessed a page Jul 24, 2017 at 19:49
  • You could add a model called Page that has a one to many relationship with User. From there you could track detailed information regarding Page (i.e: type of page accessed, when the user accessed the page, and the total amount of pages accessed).
    – the12
    Jul 24, 2017 at 19:54
  • @the12 joins this common will be too expensive. I'm just creating an access hash with keys the dates and values the page id. This is much less complex as well. I think I would implement it this way regardless of the joins Jul 24, 2017 at 20:41
  • 1
    More reasons not to use class variables: they are not threadsafe in Rails.
    – anothermh
    Jul 24, 2017 at 22:54

1 Answer 1

2

You can't do it this way. You must operate on the presumption that your Rails application will consist of multiple independent processes with entirely arbitrary lifetimes, that is they may be spawned if needed and killed if they're idle at any time.

You're stuck having to persist this somewhere. A flat file can work if you're using a single server, but a database of some sort, SQL or otherwise, is also viable. For light loads, that is less than dozens of requests per second, SQL won't be a problem.

2
  • I know this is not what I want for my application, but are there any gems for managing centralized state? Jul 24, 2017 at 20:19
  • 1
    A database is the easiest way to do this. Please, for your own sanity, do not reinvent something as fundamental as this. There's absolutely no reason. Adding a page where the administrator can change the value and save that value in the database is trivial. Writing your own multi-process RPC broadcasting system is hard.
    – tadman
    Jul 24, 2017 at 20:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.