简体   繁体   中英

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, along 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 (eg 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, eg

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM