Is it possible to dynamically remove a level of rails resource nesting?

十年热恋 提交于 2019-12-06 06:04:05

interesting question. i think it might be possible to do this using request-based constraints.

in an initializer, define a constant :

 YOUR_HOST = 'jobsrus.com'.freeze

then in routes.rb :

 constraints :host => /!#{YOUR_HOST}/ do
   resources :jobs
 end

 resources :companies do
   resources :jobs
 end

the order here is important : if request.host does not match your host name, the first set of routes is available and captures the request before it hits the second set.

but now, you will need to make changes to your controller, so that it can retrieve the company and scope the jobs resources accordingly ( didnt try this, use with caution ):

class JobsController < ApplicationController
  before_filter :resolve_whitelabel

  def resolve_whitelabel
    if request.host != YOUR_HOST
      # not safe as is, just demonstrates the idea
      @client      = Company.find_by_host( request.host ) 
      @scoped_jobs = Job.where( company_id: @client.id ) 
    else
      @scoped_jobs = Job
    end    
  end


  def scoped_jobs
    @scoped_jobs
  end

  def index
    # just an example
    @jobs = scoped_jobs.recent 
  end
end 

you just have to remember always to use the scoped_jobs.

Edit

You can "store" a block in a Proc :

routes = Proc.new do
           resources :jobs
         end

... and then you should be able to convert back this Proc into a block using the & operator :

constraints( :host => /!#{YOUR_HOST}/, &routes )
resources( :companies, &routes )

this needs to be tested, i never used it in this context. Be aware, in particular, that a Proc acts as a closure : it captures its context (variables available in this scope, etc. This is called its 'binding') when it is created (much as a block does). This may lead to unexpected behaviour (though i don't think it will matter in that case, because your Proc's scope is the same as the original block's one).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!