views:

26

answers:

2

I have the following variable definition:

@monday = (Time.now).at_beginning_of_week

I use that in different models, controllers, and views.

Where can I define it (and how should I define it -- @@? ) so I can define it once and use throughout my Rails application?

Should it be in environment.rb? Should it be a @@?

A: 

Defining this value using environment.rb is not what you want, because the value would be calculated when the server starts and will remain fixed after that. If you want the value to be refreshed every week, this is a problem.

I would go with the class variable (@@) in ApplicationController. But this is not accessible in the model.

What you can do is create a new module, define this value in this module, and mixin this module in any controller or model that needs it. So you would have MyModule::start_of_week with the value. Just ensure that this value gets set on every request.

Faisal
+1  A: 

I would add it to application controller:

before_filter :load_date

def load_date
  @monday =  (Time.now).at_beginning_of_week
end

So it will be accessible in all of yours controllers and views. If you want to use it in your models, then probably you need it as some param, on example for scopes. Then your controller is place where you should pass this variable to model:

@models = MyModel.before_date(@monday)

I don't think you need to have only one instance of this variable for whole application. Initializing it is quite simple. Also it is not good when you initialize it and don't use it. For me it is hard to imagine that you need it in all of your controllers and actions.

The other way is you can define class:

class MyDate
  def self.get_monday
    Time.now.at_beginning_of_week
  end
end

And put it in config/initializers (probably there is better place where to put it). Then you can access it from anywhere in your application:

MyDate::get_monday
klew
It is in about three controllers and views (and I think only 1 model) -- but I noticed I defined it differently in three different laces so wanted to make it DRY. If I put it in the /lib file would that work? Would the file have to be named my_date.rb?
Angela