module RackWarden::RespondWith::Helpers

Public Instance Methods

respond_to(&block) click to toggle source
# File lib/rack_warden/sinatra/respond_with.rb, line 183
def respond_to(&block)
  Format.new(self).finish(&block)
end
respond_with(template, object = nil, &block) click to toggle source
# File lib/rack_warden/sinatra/respond_with.rb, line 148
def respond_with(template, object = nil, &block)
  object, template = template, nil unless Symbol === template
  format = Format.new(self)
  format.on "*/*" do |type|
    exts = settings.ext_map[type]
    exts << :xml if type.end_with? '+xml'
    # WBR - not necessary, since the hack of #finish method above.
    #exts.unshift params[:format].to_sym if params[:format]
    logger.debug "RW respond_with format: #{params[:format]}"
    
    logger.debug "RW respond_with exts: #{exts.inspect}"
    if template
      args = template_cache.fetch(type, template) { template_for(template, exts) }
      if args.any?
        locals = { :object => object }
        locals.merge! object.to_hash if object.respond_to? :to_hash

        renderer = args.first
        options = args[1..-1] + [{:locals => locals}]

        halt send(renderer, *options)
      end
    end
    if object
      exts.each do |ext|
        halt json(object) if ext == :json
        next unless object.respond_to? method = "to_#{ext}"
        halt(*object.send(method))
      end
    end
    false
  end
  format.finish(&block)
end

Private Instance Methods

template_for(name, exts) click to toggle source
# File lib/rack_warden/sinatra/respond_with.rb, line 189
def template_for(name, exts)
  logger.debug "RW respond_with#template_for name, exts: #{name}, #{exts}"
  # in production this is cached, so don't worry too much about runtime
  possible = []
  settings.template_engines[:all].each do |engine|
    exts.each { |ext| possible << [engine, "#{name}.#{ext}"] }
  end
  exts.each do |ext|
    settings.template_engines[ext].each { |e| possible << [e, name] }
  end
  logger.debug "RW respond_with#template_for possible: #{possible.inspect}"
  possible.each do |engine, template|
    # not exactly like Tilt[engine], but does not trigger a require
    klass = Tilt.mappings[Tilt.normalize(engine)].first
    logger.debug "RW respond_with#template_for klass : #{klass}"
    find_template(settings.views, template, klass) do |file|
          #logger.debug "RW respond_with#template_for find_template file: #{file}"
          #logger.debug "RW respond_with#template_for find_template engine: #{engine.inspect}"
          #logger.debug "RW respond_with#template_for find_template template: #{template.inspect}"
      next unless File.exist? file
      return settings.rendering_method(engine) << template.to_sym
    end
  end
  
  [] # nil or false would not be cached
end