Module: Sinatra::RespondWith::Helpers

Includes:
JSON
Defined in:
lib/sinatra/respond_with.rb

Instance Method Summary collapse

Methods included from JSON

encode, #json

Instance Method Details

#respond_to(&block) ⇒ Object


157
158
159
# File 'lib/sinatra/respond_with.rb', line 157

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

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


130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/sinatra/respond_with.rb', line 130

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'
    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
        args << { :locals => locals }
        halt send(*args)
      end
    end
    if object
      exts.each do |ext|
        halt json(object) if ext == :json
        next unless meth = "to_#{ext}" and object.respond_to? meth
        halt(*object.send(meth))
      end
    end
    false
  end
  format.finish(&block)
end