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:



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

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



26
27
28
# File 'lib/dragonfly/url_mapper.rb', line 26

def segments
  @segments
end

#url_formatObject (readonly)

Returns the value of attribute url_format



26
27
28
# File 'lib/dragonfly/url_mapper.rb', line 26

def url_format
  @url_format
end

#url_regexpObject (readonly)

Returns the value of attribute url_regexp



26
27
28
# File 'lib/dragonfly/url_mapper.rb', line 26

def url_regexp
  @url_regexp
end

Instance Method Details

#params_for(path, query = nil) ⇒ Object



28
29
30
31
32
33
34
35
36
37
# File 'lib/dragonfly/url_mapper.rb', line 28

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
    end
    params
  end
end

#params_in_urlObject



39
40
41
# File 'lib/dragonfly/url_mapper.rb', line 39

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

#url_for(params) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/dragonfly/url_mapper.rb', line 43

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