Store query globally

Hi,
I’ve code like this

  x_data = Model.where(column: 'xyz')

and I wanted to use ‘x_data’ everywhere like models, controllers,
helpers, etc.

I used in this way

module Global
X_DATA = Model.where(column: ‘xyz’)
end

but when using Global::X_DATA it is firing query every time.

Where should I write this to use it everywhere and query should not be
fired more than once.

add this in initializers is a good practice?

Please help.

Thanks in advance.
Avantec

Avantec,

That’s actually an interesting question and you need a little knowledge
of (1) How actual global variables work in Ruby, and (2) how the Rails
boot process works, and (3) How A-Rels (ActiveRelation objects) work
under the hood.

Typically what you are trying to do is not actually done. That’s because
data in the database changes, so 98% of the time you want the query to
re-fire when it goes to look something up. To achieve that (not what you
asked for), you typically use a scope on the model.

Caching the result is the next step-up from re-firing each time. That is
often done with a memorized method, something like this:

class User
def self.all_admin_users
@all_admin_users ||= self.where(role: ‘admin’)
end
end

But note that even global variables are garbage collected when the
current process ends (which in a web scenario is when the response is
finished). So that will re-fire on the next web request.

If you truly want to load this in an initializer and have it persist
across web requests, then you would indeed do that in an initializer
during when the Rails app boots up. But that is rarely useful, since in
order to make changes to that data you would have actually restart the
entire web process. Generally it’s better just to optimize the query,
have it be a memorized method, and let it re-fire on each web request.

-Jason

On Oct 22, 2014, at 2:18 AM, Avantec V. [email protected] wrote:

module Global
Please help.
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/rubyonrails-talk/126984f291818c4ea6cf113228caf379%40ruby-forum.com.
For more options, visit https://groups.google.com/d/optout.


Jason Fleetwood-Boldt
[email protected]

All material Jason Fleetwood-Boldt 2014. Public conversations may be
turned into blog posts (original poster information will be made
anonymous). Email [email protected] with questions/concerns about
this.

Thanks Json.

Actually it is a static data and it will change rarely may be in 5 or 6
years. That’s why I don’t want to re-fire it.

If possible could you please brief about (1) How actual global variables
work in Ruby, and (2) how the Rails boot process works, and (3) How
A-Rels (ActiveRelation objects) work under the hood.

or provide any useful links

Thanks again,
avantec