123456789_123456789_123456789_123456789_123456789_

Module: Sinatra::RespondWith::Helpers

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Instance Chain:
Defined in: sinatra-contrib/lib/sinatra/respond_with.rb

Instance Method Summary

Instance Method Details

#respond_to(&block)

[ GitHub ]

  
# File 'sinatra-contrib/lib/sinatra/respond_with.rb', line 170

def respond_to(&block)
  Format.new(self).finish(&block)
end

#respond_with(template, object = nil, &block)

[ GitHub ]

  
# File 'sinatra-contrib/lib/sinatra/respond_with.rb', line 136

def respond_with(template, object = nil, &block)
  unless Symbol === template
    object = template
    template = nil
  end
  format = Format.new(self)
  format.on '*/*' do |type|
    exts = settings.ext_map[type]
    exts << :xml if type.end_with? '+xml'
    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..] + [{ 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

#template_for(name, exts) (private)

[ GitHub ]

  
# File 'sinatra-contrib/lib/sinatra/respond_with.rb', line 176

def template_for(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

  possible.each do |engine, template|
    klass = Tilt.default_mapping.template_map[engine.to_s] ||
            Tilt.lazy_map[engine.to_s].fetch(0, [])[0]

    find_template(settings.views, template, klass) do |file|
      next unless File.exist? file

      return settings.rendering_method(engine) << template.to_sym
    end
  end
  [] # nil or false would not be cached
end