Nathan
Nathan

Reputation: 60

Ruby on Rails - Use date to trigger action

I have an object that has an end date which is created using the callback after_create.

I'm wondering where the best place is to include the logic which would trigger an action when the object expires. (Time.now.in_time_zone > Object.end_date)

I'd like to create a method that checks whether an object has the attribute repeat as true or false. If it's true and the current date is passed the end date of the object, it should add 7 days to the end date of the object.

I have a method which checks whether the object is still valid but it's a boolean and I use it multiple times in the view so if I include it there, it gets executed multiple times before the view is even updated and I end up adding too many days to the end date.

Is it possible to have an action in your view file which is called automatically when the page loads if it falls under a certain condition? I'm guessing this is bad practice because I've read a few articles about avoiding too much logic in your view files.

I'm sure there are many ways of doing this so could you please let me know what methods you've used to overcome this?

Let me know if you need any more information.

Upvotes: 1

Views: 677

Answers (1)

Phil
Phil

Reputation: 2807

You could consider using a Controller before_action, which would be called as you mentioned before the page loads.

Adapting the example in the Rails docs at http://guides.rubyonrails.org/action_controller_overview.html#filters

class MyObjectsController < ActionController::Base
  before_action :object_expire, only: [:show]

  private

  def object_expire
    # perform some logic here
    if @my_object.expired?
      @expired_result = @my_object.do_repeat
    end  
  end
end

EDIT - limit before_action to show actions only

Upvotes: 1

Related Questions