Class: Dragonfly::UrlMapper

Inherits:
Object show all
Defined in:
lib/dragonfly/url_mapper.rb

Defined Under Namespace

Classes: BadUrlFormat, Segment

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url_format, patterns = {}) ⇒ UrlMapper

Returns a new instance of UrlMapper

Raises:



16
17
18
19
20
21
# File 'lib/dragonfly/url_mapper.rb', line 16

def initialize(url_format, patterns={})
  @url_format = url_format
  raise BadUrlFormat, "bad url format #{url_format}" if url_format[/[\w_]:[\w_]/]
  init_segments(patterns)
  init_url_regexp
end

Instance Attribute Details

#segmentsObject (readonly)

Returns the value of attribute segments



23
24
25
# File 'lib/dragonfly/url_mapper.rb', line 23

def segments
  @segments
end

#url_formatObject (readonly)

Returns the value of attribute url_format



23
24
25
# File 'lib/dragonfly/url_mapper.rb', line 23

def url_format
  @url_format
end

#url_regexpObject (readonly)

Returns the value of attribute url_regexp



23
24
25
# File 'lib/dragonfly/url_mapper.rb', line 23

def url_regexp
  @url_regexp
end

Instance Method Details

#params_for(path, query = nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
# File 'lib/dragonfly/url_mapper.rb', line 25

def params_for(path, query=nil)
  if path and md = path.match(url_regexp)
    params = Rack::Utils.parse_query(query)
    params_in_url.each_with_index do |var, i|
      value = md[i+1][1..-1] if md[i+1]
      params[var] = value && Utils.uri_unescape(value)
    end
    params
  end
end

#params_in_urlObject



36
37
38
# File 'lib/dragonfly/url_mapper.rb', line 36

def params_in_url
  @params_in_url ||= url_format.scan(/\:[\w_]+/).map{|f| f.tr(':','') }
end

#url_for(params) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/dragonfly/url_mapper.rb', line 40

def url_for(params)
  params = params.dup
  url = url_format.dup
  segments.each do |seg|
    value = params[seg.param]
    value ? url.sub!(/:[\w_]+/, Utils.uri_escape_segment(value.to_s)) : url.sub!(/.:[\w_]+/, '')
    params.delete(seg.param)
  end
  url << "?#{Rack::Utils.build_query(params)}" if params.any?
  url
end