1

I have a rails application where I display some results based on a date range. I am using some global variables to set the dates. My code looks like below:

#index.html.erb 

  <td>From: <%= $from %></td>
  <td>To: <%= $to - 1.day%></td>


#controller

if (params[:first] || params[:next] || params[:previous])
    if params[:first]
        $from = Date.today - 7.day
        $to = Date.today + 1.day
    end

    if params[:next]
        $from = $from - 7.day
        $to = $to - 7.day
    end 

    if params[:previous]
        if $to != Date.today + 1.day
             $to = $to + 7.day
             $from = $from + 7.day
        end
    end 
end

This code seems to work fine, but when I access the application from more than one machine, it is a mess as the global variables are not unique for each instance I guess.

So I tried to use @variable (instance variables) instead of global variables. But whenever I submit the page from the view, all the variables get reset to NULL and the values don't persist to the controller. Can someone suggest me some pointers to deal with the problem here.

3
  • How are you 'submitting the view'? Commented Mar 27, 2013 at 22:32
  • @ramblex : That's my last option....:( Commented Mar 27, 2013 at 22:37
  • possible duplicate of Ruby on Rails - Avoiding Global Variables Commented Mar 27, 2013 at 23:11

1 Answer 1

2

Without more context it's unclear what your specific problem is. That said:

Controllers are instantiated per request: instance variables are obviously reset between requests.

Perhaps a before_filter and/or some utility methods to instantiate those from/to vars?

Also, the wrapper around each param's if statements seems redundant; is it really necessary?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.