Class: Rad::Router::RestfulRouter

Inherits:
Object
  • Object
show all
Includes:
AbstractRouter
Defined in:
lib/rad/router/_restful_router.rb

Instance Method Summary collapse

Constructor Details

#initializeRestfulRouter

Returns a new instance of RestfulRouter.



4
5
6
# File 'lib/rad/router/_restful_router.rb', line 4

def initialize
  @resources, @class_names = {}, {}
end

Instance Method Details

#add(resource, options = {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/rad/router/_restful_router.rb', line 8

def add resource, options = {}
  # parsing options
  options.validate_options! :class_name, :url_root, :prefix
  resource = resource.to_s
  resource.must_not =~ /\//
  raise "resource should be in plural form!" unless resource.pluralize == resource
  class_name = options.delete(:class_name) || raise("no class name!")
  class_name.must_be.a String
  url_root = parse_url_root options
  prefix = parse_prefix options

  # logic
  meta = Meta.new
  meta.merge!(
    class_name: class_name,
    resource: resource,
    url_root: url_root,
    prefix: prefix
  )

  resources.must_not.include(resource.pluralize)
  class_names.must_not.include(class_name)
  resources[resource.pluralize] = meta
  resources[resource.singularize] = meta
  class_names[class_name] = meta
end

#decode(path, params) ⇒ Object



54
55
56
# File 'lib/rad/router/_restful_router.rb', line 54

def decode path, params
  decode_as_object_resource(path, params) || decode_as_static_resource(path, params)
end

#encode(klass, method, params) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/rad/router/_restful_router.rb', line 35

def encode klass, method, params
  meta = class_names[klass.name]
  return nil unless meta

  path = if id = params.delete(:id)
    "/#{meta[:resource]}/#{id}/#{method}"
  else
    "/#{meta[:resource]}/#{method}"
  end

  prefix = meta[:prefix]
  path = encode_prefix_params! path, params, prefix if prefix

  url_root = meta[:url_root]
  params[:url_root] = url_root if url_root

  [path, params]
end

#encode_method(route_method, has_id) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/rad/router/_restful_router.rb', line 58

def encode_method route_method, has_id
  token = route_method.sub(/_path$/, '')

  resources.each do |name, meta|
    if i = token.rindex(name)
      route_method.size == i + name.size and route_method[(i-1)..(i-1)] == '_'
      return meta.get_class, route_method[0..(i-2)].to_sym
    end
  end

  return nil
end