views:

35

answers:

1

Wow crazy title! But here's the problem. In efforts to dry up my school website management system application, I've made a module of my application (FileSet) restful and placed it in one place. Previously FileSet was used in the general website system, and also in a kids learning area system. They both behaved exactly the same except for one nuance. In the kids area, FileSet Files were divided into two categories, startup, and normal. Startup files are the ones that teachers have made, normal ones are the ones kids have made. Now in the general website app, this distinction isn't relevant and so is ignored. Here's the tough part. I want to use the same controllers and views in both contexts. At runtime I know that a fileset belongs either to the general site, or to this learning area, so I can say that if it's in the learning area context, i want to constrain FileSet.find(x).files to only use the 'normal' named scope. If the context is the normal website, then we'll just not use a named scope at all.

I've simplified the information above, but basically the question is, how can I call FileSet.find(x).files and have the files method be smart enough to narrow the results returned based upon the runtime context?

I've explored association extension a bit, but that doesn't seem to do the job. I'm hoping something exists here. I'm trying desperately to keep this logic in the model and not have the views or controllers concerned with it. Default scopes would work a treat if they were evaluated at runtime :)

Looking forward to some suggestions :)

Cheers,

Brendon

+1  A: 

Can you use a named scope with a proc that determines the current context and return the appropriate conditions? Something like this in File:

named_scope :for_context, :conditions => lambda { 
  if only_normal?
    { :type => 'normal' }
  elsif only_startup?
    { :type => 'normal' }
  else
    {}
  end
}

then you could call:

FileSet.find(x).files.for_context
Arthur
Thanks Arthur, that'll probably have to be the way. I just realised that I'll also need to filter based upon a controller condition (whether the user is in the admin area or not) so I'll have to call a scope and pass through the current context :) Thanks for your suggestion :)
Brendon Muir