Class: Webmate::Routes::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/webmate/routes/base.rb

Constant Summary collapse

FIELDS =
[:method, :path, :action, :transport, :responder, :route_regexp, :static_params]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ Base

method: GET/POST/PUT/DELETE path : /user/123/posts/123/comments transport: HTTP/WS/ responder: class, responsible to ‘respond’ action action: method in webmate responders, called to fetch data static params: additional params hash, which will be passed to responder

for example, { :scope => :user }


15
16
17
18
19
20
21
22
23
24
# File 'lib/webmate/routes/base.rb', line 15

def initialize(args)
  values = args.with_indifferent_access
  FIELDS.each do |field_name|
    instance_variable_set("@#{field_name.to_s}", values[field_name])
  end

  normalize_data
  create_matching_regexp
  create_substitution_attrs
end

Instance Attribute Details

#regexpObject (readonly)

Returns the value of attribute regexp.



5
6
7
# File 'lib/webmate/routes/base.rb', line 5

def regexp
  @regexp
end

#substitution_attrsObject (readonly)

Returns the value of attribute substitution_attrs.



5
6
7
# File 'lib/webmate/routes/base.rb', line 5

def substitution_attrs
  @substitution_attrs
end

Instance Method Details

#match(request_path) ⇒ Object

method should check coincidence of path pattern and given path ‘/projects/qwerty123/tasks/asdf13/comments/zxcv123’ will be parsed with route /projects/:project_id/tasks/:task_id/comments/:comment_id and return

result = {
  action: 'read',
  responder: CommentsResponder,
  params: {
    project_id: 'qwerty123',
    task_id: :asdf13,
    comment_id: :zxcv123
  }
}


41
42
43
44
45
46
47
48
49
# File 'lib/webmate/routes/base.rb', line 41

def match(request_path)
  if regexp.match(request_path)
    {
      action: action,
      responder: responder,
      params: (static_params || {}).merge(params_from_path(request_path))
    }
  end
end

#params_from_path(path) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/webmate/routes/base.rb', line 51

def params_from_path(path)
  match_data = regexp.match(path)
  params = {}
  substitution_attrs.each_with_index do |key, index|
    if key == :splat
      params[key] ||= []
      params[key] += match_data[index.next].split('/')
    else
      params[key] = match_data[index.next]
    end
  end
  params
end