Module: Roda::RodaPlugins::Json

Defined in:
lib/roda/plugins/json.rb

Overview

The json plugin allows match blocks to return arrays or hashes, and have those arrays or hashes be converted to json which is used as the response body. It also sets the response content type to application/json. So you can take code like:

r.root do
  response['Content-Type'] = 'application/json'
  [1, 2, 3].to_json
end
r.is "foo" do
  response['Content-Type'] = 'application/json'
  {'a'=>'b'}.to_json
end

and DRY it up:

plugin :json
r.root do
  [1, 2, 3]
end
r.is "foo" do
  {'a'=>'b'}
end

By default, only arrays and hashes are handled, but you can automatically convert other types to json by adding them to json_result_classes:

plugin :json
json_result_classes << Sequel::Model

Defined Under Namespace

Modules: ClassMethods, RequestMethods

Class Method Summary collapse

Class Method Details

.configure(app) ⇒ Object

Set the classes to automatically convert to JSON



38
39
40
41
42
# File 'lib/roda/plugins/json.rb', line 38

def self.configure(app)
  app.instance_eval do
    @json_result_classes ||= [Array, Hash]
  end
end