Class: HTTPAccept::MediaType

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/http_accept/media_type.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ MediaType

Returns a new instance of MediaType.



7
8
9
10
# File 'lib/http_accept/media_type.rb', line 7

def initialize(args = {})
  self.format = args[:format]
  self.params = args[:params] || {}
end

Instance Attribute Details

#formatObject

Returns the value of attribute format.



5
6
7
# File 'lib/http_accept/media_type.rb', line 5

def format
  @format
end

#paramsObject

Returns the value of attribute params.



5
6
7
# File 'lib/http_accept/media_type.rb', line 5

def params
  @params
end

Instance Method Details

#<=>(other) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/http_accept/media_type.rb', line 12

def <=>(other)
  # return -1 if more specific than other, so we end up at the front of the
  # array
  if q > other.q
    -1
  elsif q < other.q 
    1
  elsif !all_subtypes? && other.all_subtypes? ||
    !all_types? && other.all_types?
    -1
  elsif all_subtypes? && !other.all_subtypes? ||
    all_types? && !other.all_types?
    1
  elsif params.count == other.params.count
    0
  elsif params.count > other.params.count
    -1
  else
    1
  end
end

#all_subtypes?Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/http_accept/media_type.rb', line 34

def all_subtypes?
  format.match(/\/\*\Z/) != nil
end

#all_types?Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/http_accept/media_type.rb', line 38

def all_types?
  format == "*/*"
end

#qObject



42
43
44
# File 'lib/http_accept/media_type.rb', line 42

def q
  params["q"] ? params["q"].to_f : 1.0
end

#to_hObject



46
47
48
# File 'lib/http_accept/media_type.rb', line 46

def to_h
  { :format => format, :params => params }
end

#to_sObject



50
51
52
53
54
55
56
# File 'lib/http_accept/media_type.rb', line 50

def to_s
  if params.count > 0
    format + "; " + params.map { |k, v| "#{k}=#{v}" }.join("; ")
  else
    format
  end
end