Module: Jets::Router::Route::AfterInitialize

Included in:
Jets::Router::Route
Defined in:
lib/jets/router/route/after_initialize.rb

Instance Method Summary collapse

Instance Method Details

#after_initializeObject



3
4
5
6
7
8
# File 'lib/jets/router/route/after_initialize.rb', line 3

def after_initialize
  normalize_to_option!
  normalize_path_option!
  normalize_id_constraint!
  check_on_option!
end

#check_on_option!Object



52
53
54
55
56
# File 'lib/jets/router/route/after_initialize.rb', line 52

def check_on_option!
  if @options[:on] && !%w[resources resource].include?(@scope.from.to_s)
    raise Jets::Router::Error.new("ERROR: The `on:` option can only be used within a resource or resources block")
  end
end

#escape_path(path) ⇒ Object



58
59
60
61
62
# File 'lib/jets/router/route/after_initialize.rb', line 58

def escape_path(path)
  path.to_s.split('/').map { |s| s =~ /\A[:\*]/ ? s : CGI.escape(s) }.join('/')
  path = "/#{path}" unless path.starts_with?('/')
  path
end

#normalize_id_constraint!Object



46
47
48
49
50
# File 'lib/jets/router/route/after_initialize.rb', line 46

def normalize_id_constraint!
  if @options[:id] && !@options[:constraints]
    @options[:constraints] = { id: @options[:id] }
  end
end

#normalize_path_option!Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/jets/router/route/after_initialize.rb', line 31

def normalize_path_option!
  path = @options[:path]
  resource_name = @scope.resource_name
  if path.is_a?(Symbol) and resource_name # Treat as controller action
    # Only supported with used within scope, resource, resources block
    action = path # IE: get :list => action = :list
    controller = @scope.virtual_controller
    # infer and set to option if not set
    @options[:to] ||= "#{controller}##{action}"
  end

  # override
  @options.merge!(path: escape_path(path)) if path
end

#normalize_to_option!Object

Possibly infer to option from the path. Example:

get 'posts/index'
get 'posts', to: 'posts#index'

get 'posts/show'
get 'posts', to: 'posts#show'


18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/jets/router/route/after_initialize.rb', line 18

def normalize_to_option!
  return if @options[:to]

  path = @options[:path].to_s
  return unless path.include?('/')

  path = path.delete_prefix('/') # remove leading slash
  items = path.split('/')
  if items.size == 2
    @options[:to] = items.join('#')
  end
end