Search code examples
ruby-on-railsrubycamping

Camping: Return user to recent entries, but keep errors


Users can view a specific entry in my webapp with a URL. /entry/8, for example. If an entry doesn't exist, "Entry not found" gets appended to @messages and I render an error page.

I'd like to show some arbitrary query instead of a blank page, but I can't figure out a good way to keep the error message around to be displayed. There are other actions that need to take place in the arbitrary query's controller, so I can't just duplicate the query and render :posts.

Some example code:

module MyApp::Controllers
  class ComplexQuery < R '/query'
    def get
      @entries = Entries.all(:conditions => someComplexConditions)
      until @entries.complexEnough? then @entries.makeMoreComplex! end
    end
  end

  class SingleEntry < R '/entry/(\d+)'
    def get(id)
      @entries = Entries.find_all_by_id(id)
      unless @entries.nil?
        render :posts
      else
        @messages = ["That entry does not exist."]
        render :blank  # I want to run Controllers::ComplexQuery, instead of rendering a blank page.
      end
    end
  end
end

Solution

  • Something like this?

    def get(id)
      @entries = Entries.find_all_by_id(id)
      unless @entries.nil?
        render :posts
      else
        r *MyApp.get(:ComplexQuery)
      end
    end
    

    See Camping.method_missing.

    But I would also recommend moving ComplexQuery into a helper method:

    module MyApp::Helpers
      def complex_query(conditions); end
    end
    

    Then you can complex_query(something) in both SingleEntry and ComplexQuery.