Andrew France wrote:
> >> The trouble with this is that controller methods are actions, not
> controller code. �Anything else belongs in a model or a helper.
I completely agree with Marnen. Fat models, skinny controllers.
Your example is a poor one - it's certainly appropriate to have a
@book instance variable in the BooksController. Your instinct is
correct about lots of instance variables, but they should usually be
replaced with model instance methods.
Which is a philosophy I try to subscribe to, but there are many
instances where I wish to pass multiple values to a view. Perhaps
because the data is not related in the database or I wish to control
the dataset that is passed to the view.
For example, if I have a show action for Book, as a convenience I may
wish to display all the authors on the system that the user can
access:
def show
@book = Book.find(params[:id])
@all_authors = Author.all
end
Is that not reasonable?
I think it is. You're doing simple calls to model methods and
displaying the results.
It's a contrived and simplified example of what I deal with in most
apps, where I need to get data from unrelated models. Or sometimes I
may create instance variables from related data (e.g. @authors =
@book.authors) because I wish to re-use the view in other controllers.
Right. If you do a lot of that, perhaps you should introduce a
presenter.
So with my suggestion it could be written as (short block syntax):
var(:book) { Book.find(params[:id]) }
var(:all_authors) { Author.all }
var(:authors) { book.authors }
Is that better or worse? Harder to read or improves comprehension? Or
has no purpose at all?
No purpose at all, I'd say. It seems pretty well equivalent to the
first form
The problem with instance variables is that my view is not inside the
controller class, so it's reasonable to ask if it's appropriate for
these variables to appear 'outside' of their class.
It's the Rails way, thanks to some magic. It's not that the variables
appear outside their class; rather, the values are copied from the
controller to the view.
It is also easy to
forget to set the variable in the controller, which is often done on
purpose and checked for in view logic.
And the same is true with your proposal.
But by replacing instance
variables with methods you are creating a more explicit interface
contract that you expect one or more controllers to adhere to.
No. The two interfaces are equivalent, and created the same contract.
However, your implementation puts methods in the controller that don't
belong there. This is a bad idea.
Thanks,
Andrew
Best,