rails - DRY respond_to with repeated actions

前端 未结 2 1328
谎友^
谎友^ 2021-01-11 10:46

In one of my rails controller, I must respond to several types of formats, so I use the typical respond_to chain:

respond_to do |format|
  forma         


        
2条回答
  •  一整个雨季
    2021-01-11 11:21

    Can you give an example of the repetition you're seeing?

    You could always do something like this:

    respond_to do |do|
      format.html { common_stuff }
      format.mobile { common_stuff }
      format.xml { common_stuff }
      ...
    end
    
    protected 
    
    def common_stuff
      ...
    end
    

    I think something like that could be refactored to (I probably got this wrong as I always forget how to use a method as a block:

    [:html, :mobile, :xml].each { |f| format.send(:f, lambda{ common_stuff }) }
    

    Having said that, I think you're better off with the former as it's more explicit.

提交回复
热议问题