Module: Rack::RespondTo::Helpers

Included in:
MediaType
Defined in:
lib/sinatra/rack_accept.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object

This code was inherited from respond_to plugin github.com/cehoffman/sinatra-respond_to

This method is used to overide the default content_type returned from rack-accept middleware.



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/sinatra/rack_accept.rb', line 52

def self.included(klass)
  klass.class_eval do
    alias_method :original_content_type, :content_type

    def content_type(*args)
      original_content_type(*args)
      request.env['rack-accept.formats'] = { args.first.to_sym => 1 }
      response['Content-Type']
    end

  end
end

Instance Method Details

#accepting_formatsObject



65
66
67
# File 'lib/sinatra/rack_accept.rb', line 65

def accepting_formats
  request.env['rack-accept.formats']
end

#respond_to {|wants| ... } ⇒ Object

Yields:

  • (wants)


75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/sinatra/rack_accept.rb', line 75

def respond_to(&block)
  wants = {}
  def wants.method_missing(type, *args, &handler)
    self[type] = handler
  end
  yield wants

  if request.env["SCRIPT_NAME"].include?("cimi") || Deltacloud.default_frontend.name == :cimi
    #when cimi and neither json or xml defined... default to _something_  -  json?
    if ([:json, :xml] & accepting_formats.keys).empty?
      request.env['rack-accept.formats'] = {:json=>0}
    end
    @media_type = (accepting_formats.has_key?(:xml) ? [:xml, accepting_formats[:xml]] : nil)
  end if Deltacloud.respond_to? :default_frontend

  @media_type ||= accepting_formats.to_a.sort { |a,b| a[1]<=>b[1] }.reverse.select do |format, priority|
    wants.keys.include?(format) == true
  end.first
  if @media_type and @media_type.kind_of? Symbol
    @media_type = [ @media_type ]
  end
  if @media_type and @media_type[0]
    @media_type = @media_type[0]
    if  Rack::MediaType::ACCEPTED_MEDIA_TYPES[@media_type]
      headers 'Content-Type' => Rack::MediaType::ACCEPTED_MEDIA_TYPES[@media_type][:return]
    else
      headers 'Content-Type' => 'application/xml'
    end
    wants[@media_type.to_sym].call if wants[@media_type.to_sym]
  else
    headers 'Content-Type' => nil
    status 406
  end
end

#static_file?(path) ⇒ Boolean

Returns:

  • (Boolean)


69
70
71
72
73
# File 'lib/sinatra/rack_accept.rb', line 69

def static_file?(path)
  public_dir = File.expand_path(settings.public)
  path = File.expand_path(File.join(public_dir, unescape(path)))
  path[0, public_dir.length] == public_dir && File.file?(path)
end