Krzysztof Witczak
Krzysztof Witczak

Reputation: 512

Ruby on Rails naming convention in view

In the RoR view You often need to display lists of some models. If You use instance variables for this, like @people and countries, RubyMine IDE will warn You that You should use at most two instance variables in the view.

So let's say You will wrap those in a hash, like:

view_params = { people: @people, countries: @countries }

I know naming is very important in RoR. Is there any naming convention for such hash, which I called view_params (in Django they call it context I guess), or good practice how to deal with this problem?

Upvotes: 1

Views: 162

Answers (2)

ReggieB
ReggieB

Reputation: 8212

It's a stupid rule. Turn off the rule in your IDE.

Stick to the better rule - "Methods can be no longer than five lines of code." If you find your controller methods becoming longer than five lines because you're building too many instance variable - then package them up. But if you can create all the instance variables you want in about 5 lines of code, then that's fine.

If you look at the example in Sandi Metz Rules For Developers, all they've done is package the instance variables into another object. Is there really a good reason why having two instance variables associated with a controller instance is worse than making them belong to a new object instance?

For me:

def index
  @foo = Foo.get_some
  @bar = Bar.get_some
end

Is cleaner and simpler than:

class FooBar
  attr_reader :foo, :bar
  def initialize(foo, bar)
    @foo = foo
    @bar = bar
  end
end

class FooBarController

  def index
    foo = Foo.get_some
    bar = Bar.get_some
    @foo_bar = FooBar.new(foo, bar)
  end

end

Upvotes: 3

baron816
baron816

Reputation: 701

Use a non-active record ruby class instead of a hash. One instance variable is probably best. See facade pattern: https://robots.thoughtbot.com/sandi-metz-rules-for-developers

Upvotes: 1

Related Questions