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

- (UrlMapper) initialize(url_format, patterns = {})

Returns a new instance of UrlMapper

Raises:



13
14
15
16
17
18
# File 'lib/dragonfly/url_mapper.rb', line 13

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

- (Object) segments (readonly)

Returns the value of attribute segments



20
21
22
# File 'lib/dragonfly/url_mapper.rb', line 20

def segments
  @segments
end

- (Object) url_format (readonly)

Returns the value of attribute url_format



20
21
22
# File 'lib/dragonfly/url_mapper.rb', line 20

def url_format
  @url_format
end

- (Object) url_regexp (readonly)

Returns the value of attribute url_regexp



20
21
22
# File 'lib/dragonfly/url_mapper.rb', line 20

def url_regexp
  @url_regexp
end

Instance Method Details

- (Object) params_for(path, query = nil)



22
23
24
25
26
27
28
29
30
31
# File 'lib/dragonfly/url_mapper.rb', line 22

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

- (Object) params_in_url



33
34
35
# File 'lib/dragonfly/url_mapper.rb', line 33

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

- (Object) url_for(params)



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/dragonfly/url_mapper.rb', line 37

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