[LRUG] Proffer and introducing constraints to Rails

Andrew Stewart boss at airbladesoftware.com
Mon Apr 2 11:55:52 PDT 2012


On 2 Apr 2012, at 17:05, James Hunt wrote:
> How much more convenient is it though? How much time do you really save by having instance variables by default? 

Compared to the Java way, which is where I came from when I switched to Rails, using `@post` in a view is far more convenient than `((Post) request.getParameter("post"))` (if I recall my Java from 7 years ago correctly).

Compared to Proffer, I think this:

    class PostsController < ApplicationController
      def new
        @post = Post.new
      end
    end

    <%= form_for(@post) do |f| %>
      ...
    <% end %>

-- is more convenient than this:

    class PostsController < ApplicationController
      include Proffer
      def new
        proffer :post => Post.new
      end
    end

    <%= form_for(post) do |f| %>
      ...
    <% end %>

I think it consistently saves a little bit of time.

> It's interesting to think about this the other way: if Rails had never exposed instance variables by default, would you even miss it? Would you have written a gem to add the functionality? How would you justify it?

I didn't have it before so I wouldn't have been able to miss it.  However if it vanished now I would write a gem to replace it...unless it seemed I was in a tiny minority; with Rails it's usually better to go with the flow unless there's a good reason otherwise.

> In the scheme of all the things you have to do to get a Rails app working, not having instance variables in views seems like a really small thing.

True, but a lot of Rails' productivity boost comes from the aggregation of many little time-savers.

> And if you were reaaaaallly desperate, you could do:
> 
> <% @post = post %>
> 
> at the top of your view and you're back in business! The only difference here is that before you do something like the above, you have to actually think about what you're doing and why before you do it. It's a convention: break it if you want, but know why you're doing it and what it may cost you later on.

For me, using an instance variable instead of a plain local variable is a fine convention.  If I want to share state with a view, I use an instance variable; if I don't want to share state, I use a local variable.

Cheers,
Andy




More information about the Chat mailing list