Class: Dragonfly::UrlMapper

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

Defined Under Namespace

Classes: BadUrlFormat, Segment

Constant Summary collapse

PATTERNS =
{
  basename: '[^\/]',
  name: '[^\/]',
  ext: '[^\.]',
  format: '[^\.]',
  job: '[^\/\.]'
}
DEFAULT_PATTERN =
'[^\/\-\.]'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url_format) ⇒ UrlMapper

Returns a new instance of UrlMapper.

Raises:



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

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

Instance Attribute Details

#segmentsObject (readonly)

Returns the value of attribute segments.



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

def segments
  @segments
end

#url_formatObject (readonly)

Returns the value of attribute url_format.



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

def url_format
  @url_format
end

#url_regexpObject (readonly)

Returns the value of attribute url_regexp.



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

def url_regexp
  @url_regexp
end

Instance Method Details

#params_for(path, query = nil) ⇒ Object



34
35
36
37
38
39
40
41
42
43
# File 'lib/dragonfly/url_mapper.rb', line 34

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



45
46
47
# File 'lib/dragonfly/url_mapper.rb', line 45

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

#url_for(params) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/dragonfly/url_mapper.rb', line 49

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