How to make an array available to all views.

Hi,

I have an application layout that is used to create the general layout
for all pages.
However, I seem to struggle to find out how to declare variables like
arrays so that they are available everytime that layout or its related
partials are used.

Putting @myarray = MyArray.all into every action in every controller
doesn't seem very dry, so I guess I'm just looking for a very simple
straighforward convention, but can't seem to find it documented
anywhere or figure it out.

_caps

Normally something like that goes into a high-level filter, like one
in ApplicationController.

Put a before_filter in your ApplicationController.

class ApplicationController

before_filter :set_my_array

private

def set_my_array

@myarray = MyArray.all

end

end

Cheers,

Andy

If it is literally something as simple as MyArray.all I believe there
is nothing wrong with calling the model direct from the view.

Colin

If it is literally something as simple as MyArray.all I believe there

is nothing wrong with calling the model direct from the view.

It’s dirty, horrible, bad form, breaks the separation of layers…

Don’t call the model from the view!

Andy

If it is literally something as simple as MyArray.all I believe there
is nothing wrong with calling the model direct from the view.

It's dirty, horrible, bad form, breaks the separation of layers...

Beware of the MVC police Colin, this suggestion will certanly not get
good housekeeping seal of approval :smiley:

I agree through. I'm not gonna add a before filter just to set
MyArray.all into a class variable. I'd rather call it directly and claim
to be pragmatic.

If it is literally something as simple as MyArray.all I believe there

is nothing wrong with calling the model direct from the view.

It’s dirty, horrible, bad form, breaks the separation of layers…

Beware of the MVC police Colin, this suggestion will certanly not get

good housekeeping seal of approval :smiley:

It’s not about MVC policing, I couldn’t give a monkey’s what you do in your app, but given that there is an easy way of handling it shouldn’t you describe the correct method to any new developers.

I agree through. I’m not gonna add a before filter just to set

MyArray.all into a class variable. I’d rather call it directly and claim

to be pragmatic.

How do you work out duplicating a line of code in every action is being “pragmatic”?

DRY mean anything to ya?

Cheers,

Andy

Sharagoz -- wrote:

If it is literally something as simple as MyArray.all I believe there
is nothing wrong with calling the model direct from the view.

But you are wrong. The view should never, ever, ever touch the
database.

It's dirty, horrible, bad form, breaks the separation of layers...

Beware of the MVC police Colin, this suggestion will certanly not get
good housekeeping seal of approval :smiley:

I agree through. I'm not gonna add a before filter just to set
MyArray.all into a class variable. I'd rather call it directly and claim
to be pragmatic.

Claim all you like. The fact is that in MVC architecture, database
queries don't belong in the view. A before_filter is the proper place
for this.

Best,

Sharagoz -- wrote:

If it is literally something as simple as MyArray.all I believe there
is nothing wrong with calling the model direct from the view.

But you are wrong. The view should never, ever, ever touch the
database.

Is it considered ok to call model methods if they do not touch the db,
or are model methods forbidden also?

Colin

But you are wrong. The view should never, ever, ever touch the

database.

Is it considered ok to call model methods if they do not touch the db,

or are model methods forbidden also?

I would say the view can call instance methods of the model (attributes - real and virtual) but no class methods.

So:

<%= @user.name %>

is OK, but:

<% User.first.name %>

is not. It’s a bit of a contrived example, but there you go. Accessing the model through instance variables you’ve created is OK, going directly to the model bypassing the controller is not.

Cheers,

Andy

Colin Law wrote:

Sharagoz -- wrote:

If it is literally something as simple as MyArray.all I believe there
is nothing wrong with calling the model direct from the view.

But you are wrong. �The view should never, ever, ever touch the
database.

Is it considered ok to call model methods if they do not touch the db,
or are model methods forbidden also?

I think it is appropriate for the view to call methods on the objects
passed in by the controller, provided that these methods do not change
the model or touch the database.

Example:
# controller
def my_action
  @person = Person.find(params[:id])
end

#my_action.html.erb
Good: <%= @person.name >
Bad: <% @person.save! =>
Unspeakable: <% @people = Person.all %>

Colin

Best,

Colin Law wrote:

Sharagoz -- wrote:

If it is literally something as simple as MyArray.all I believe there
is nothing wrong with calling the model direct from the view.

But you are wrong. �The view should never, ever, ever touch the
database.

Is it considered ok to call model methods if they do not touch the db,
or are model methods forbidden also?

I think it is appropriate for the view to call methods on the objects
passed in by the controller, provided that these methods do not change
the model or touch the database.

Example:
# controller
def my_action
@person = Person.find(params[:id])
end

#my_action.html.erb
Good: <%= @person.name >

What about <%= @person.group_name %>
where Person belongs to Group and group_name is an instance method of Person
def group_name
  group.name if group
end

Bad: <% @person.save! =>

I would class the above as the unspeakable one actually.

Unspeakable: <% @people = Person.all %>

Colin

Marnen Laibow-Koser wrote:

Example:
# controller
def my_action
  @person = Person.find(params[:id])
end

#my_action.html.erb
Good: <%= @person.name >
Bad: <% @person.save! =>
Unspeakable: <% @people = Person.all %>

Good example. I just want to throw in a couple more twists and see what
you think.

1. What about methods on models that change themselves in some way?

<%= @post.last_viewed_at %>

Suppose the last_viewed_at method returned a previously stored time,
then updated the model to store a new current time. Maybe a bad example,
but I hope you get my meaning.

2. What about aggregating class methods like count, sum or avg?

<%= Person.count %>

Obviously a class methods and does touch the database. I assume it would
be better to let the controller deal with stuff like this.

Controller
  @person_count = Person.count

View
  <%= @person_count %>

Thoughts anyone?

If it is literally something as simple as MyArray.all I believe there
is nothing wrong with calling the model direct from the view.

It's dirty, horrible, bad form, breaks the separation of layers...

I don't know what you mean by dirty, it saves several lines of code
and when looking at the view code it is easier to see what is
happening than to see a variable that has to be hunted for in a filter
somewhere to find out what it is.

It does not break the separation of layers any more than calling an
instance method of a model does when using something like
<%= @person.name %>

Don't call the model from the view!

@person.name is a model call from the view

Colin

It’s dirty, horrible, bad form, breaks the separation of layers…

I don’t know what you mean by dirty, it saves several lines of code

and when looking at the view code it is easier to see what is

happening than to see a variable that has to be hunted for in a filter

somewhere to find out what it is.

It saves 4 lines of code, but breaks one of the principles of MVC layered separation. I’d say the 4 lines is worth it for keeping the application clean.

Don’t call the model from the view!

@person.name is a model call from the view

I clarified my thoughts on this in a later post (10 March 2010 15:28), might I recommend reading that.

Cheers,

Andy

  1. What about methods on models that change themselves in some way?

<%= @post.last_viewed_at %>

Suppose the last_viewed_at method returned a previously stored time,

then updated the model to store a new current time. Maybe a bad example,

but I hope you get my meaning.

Don’t worry about it. What the method does
itself shouldn’t be your concern, in the view. You want your code to be
orthogonal, it shouldn’t matter how the variable returns returns the
date, or what it does when you request it, that is the model’s
prerogative. Trying to keep track all over your application of what
your model methods are doing requires you to know and consider their
internal plumbing, this couples your code that you write to the model’s
implementation. Something that won’t bite you on a small app, but will
likely turn into a nightmare on a large app.

If your view has
some object that the controller gave you, just consider it as an object
you can access in whatever way that is necessary to perform the
responsibilities of the view. Saving data is not a responsibility of
the view, so that should not happen there. Displaying the date it was
modified may possibly be a responsibility of the view, so you can
display that. If the model decides that it needs to do something every
time someone asks when it was saved, your view shouldn’t know or care
or change it’s behaviour accordingly.

Really, your view shouldn’t even know it is an ActiveRecord object, it
should just be some object that has the information necessary to get
things done. Then you can swap it out with other variables later, maybe
a struct or an object pulled from a yaml file, or whatever.

  1. What about aggregating class methods like count, sum or avg?

<%= Person.count %>

Obviously a class methods and does touch the database. I assume it would

be better to let the controller deal with stuff like this.

Controller

@person_count = Person.count

View

<%= @person_count %>

Thoughts anyone?

A variable is better here, because your view shouldn’t know how to
tabulate the size, that is business logic. What happens if you later
add another another type of user, and it should treat them as the same?
What happens if different controllers want to render that same view to
show their data? Your view knows too much about the data it is serving,
it works for Person.all, but what if you add another type of person
with different attributes, stored in the model OtherPerson ? Then you
cant use that view (or you will have to change it, and change the
controller for it).

To keep your code robust, keep your views stupid. To keep them stupid,
make sure they are agnostic towards the implementation of displaying
the data. Let the controller worry about that, that is why the
controller exists.

http://www.youtube.com/watch?v=ku3QkWcPSEw

It’s dirty, horrible, bad form, breaks the separation of layers…

I don’t know what you mean by dirty, it saves several lines of code

and when looking at the view code it is easier to see what is

happening than to see a variable that has to be hunted for in a filter

somewhere to find out what it is.

It saves 4 lines of code, but breaks one of the principles of MVC layered separation. I’d say the 4 lines is worth it for keeping the application clean.

But think how many lines of code you are going to have to go edit when you realize that you need to change it.

Also, I wouldn’t consider Person.all to be more clean than @people. What if you need to exclude some? Person.all :conditions => {whatever}, if you are just using a before filter, it is easy to override, you can override it for any given controller, and for any given controller method. If it’s hard coded into the view, then that view has to serve everybody’s wishes, it ends up having to know how it is to be used, and having lots of brittle conditional code for each of these situations.

This is why the controller must be responsible for supplying the appropriate data to the view, not the view being responsible for creating it’s own data.

It might start as innocently as Person.all, it can easily turn into

if this
Person.all
elsif that
OtherPerson.all
else
Person.all + OtherPerson.all
end

An excellent post if I may say so that brings out the salient points I
think. Can the issues be summarised as follows?

1. The controller should provide all the data that the view should
display in instance variables (@person for example).
2. The view is expected to understand the structure of the objects and
so can access attributes (virtual or otherwise) of the objects.
3. If the model needs to access the db in order to provide an
attribute value, or accessing the attribute has some side effect that
affects the db, then this is ok, providing the view does not 'know'
that the side effect or db access is happening. (Not very well written
but I hope you know what I mean).
4. The view must not call any method of the model who's purpose is to
perform an action rather than return a value.
5. The view should not make any explicit use of model classes. For
example there should be no reference to Person or any other model
class

Colin

It’s dirty, horrible, bad form, breaks the separation of layers…

I don’t know what you mean by dirty, it saves several lines of code

and when looking at the view code it is easier to see what is

happening than to see a variable that has to be hunted for in a filter

somewhere to find out what it is.

It saves 4 lines of code, but breaks one of the principles of MVC layered separation. I’d say the 4 lines is worth it for keeping the application clean.

But think how many lines of code you are going to have to go edit when you realize that you need to change it.

Did you misunderstand my post? I was arguing for putting it in a filter rather than in the view (hence saying the 4 lines of before_filter, private, def and end was worth it).

It sounds like - when you start with “But” - that you disagree, but the rest of your post seems to be arguing from the same side as my posts.

Cheers,

Andy

Yeah, I thought you were saying that not using a filter saves 4 lines of code, and is therefore cleaner, and thus worth it. Seemed to be a weird position to take, glad it was just a misunderstanding.

Huh :slight_smile:

Very nice debate and good conclusion. I think i should document it!