开发者

Rails Partials: access data via encapsulated :locals or global state (@attributes)?

I have a rails partial that renders a sidebar for users. As part of this partial, another partial is rendered that displays the user's Groups, alo开发者_如何学JAVAng with a score that is calculated from associated models of the corresponding Group. As a result, I have the following structure:

- view
   -> renders sidebar
       -> renders group_table

The sidebar partial is included in many views (e.g. show, edit, custom actions) and I have a before_filter in my controller for all these actions to set the attributes that need to be passed to the views, e.g.

@groups = @user.groups
@group_ranking = [method with heavy calculations] # access via @group_ranking[group]

Keeping the structure from above and maintaining encapsulated, self-contained partials without global state, I have to pass the @group_rankings to the group_table partial via the sidebar partial (which does nothing with it than passing it on). Since the sidebar does also include further partials requiring different data, this gets really ugly (besides, I have code repetition when rendering the sidebar in my views, always passing the same @ variables to it).

So the final question is: Is this acceptable to enforce encapsulated views, is there a better way to do it, or would it be OK to access the @variables in my partials directly?

Thanks!


My advise is to avoid relying on instance variables in helpers and partials.

It makes them less intuitive and much harder to maintain and test.

You should not trade clarity for dryness, so keep on using local variables.


I think this is one of those times where instance variables are ok. Where does the sidebar live? I suspect there's no model or controller specific to it, so this partial exists in the application view folder (or is freeloading on another controller's views). I'd put all such partials in their own folder... views/global or something, that helps indicate that they have unique needs in instance variables.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜