Class: Ptero::Generator::RoutesGenerator

Inherits:
PHPGenerator show all
Defined in:
lib/ptero/generators/routesgenerator.rb

Overview

A generator for the application routes file

Instance Attribute Summary collapse

Attributes inherited from Ptero::Generator

#app, #dir, #name

Instance Method Summary collapse

Methods inherited from PHPGenerator

#extension, #path

Methods inherited from Ptero::Generator

const_missing, #content, #content_params, #extension, #filename, #generate, #generated?, #location, #path, #reload, #remove, #template_path, #to_s, #type

Constructor Details

#initialize(routes = {}) ⇒ RoutesGenerator

Initialize as a generator, name is always “routes”

Parameters:

  • routes (Hash) (defaults to: {})

    a list of route mappings from path to controller-name



16
17
18
19
20
# File 'lib/ptero/generators/routesgenerator.rb', line 16

def initialize(routes = {})
  super('routes')
  @routes = routes
  
end

Instance Attribute Details

#routesObject (readonly)

Returns the value of attribute routes.



22
23
24
# File 'lib/ptero/generators/routesgenerator.rb', line 22

def routes
  @routes
end

Instance Method Details

#get_current_routesPtero::Generator::RoutesGenerator

Open the routes.rb file and parse out any existing routes into this object



54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/ptero/generators/routesgenerator.rb', line 54

def get_current_routes
  raise Ptero::Exception::GeneratorException, "Routes file: #{location} not found" unless File.exist? location
  File.open(location,'r') do |file|
    file.each_line do |line|
      line.match( /^\s*(['"])([\/\w:\.]+)\1\s*=>\s*(['"])#{app.name}\\Controllers\\(\w+)Controller\3,?\s*$/ ) do |match|
        key = match[2]
        value = match[4]
        @routes[key] = value
      end
    end
  end
  self
end

#route(path, controller) ⇒ Object

Add a new route to routes.php

Parameters:

  • path (String)

    the path of the new route

  • controller (String)

    the name of the route’s controller

Raises:



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/ptero/generators/routesgenerator.rb', line 27

def route(path,controller)
  get_current_routes
  raise Ptero::Exception::GeneratorException, "Route #{path} already exists" if @routes.has_key? path
  controller = "#{controller[0].upcase}#{controller[1,controller.length-1]}"
  @routes[path] = controller
  Mute::IO.capture_stdout do
    reload
  end
  puts "ROUTE - #{path} => #{controller}Controller".blue
  self
end

#unroute(path) ⇒ Object

Remove a route from routes.php

Parameters:

  • path (String)

    the path of the route to be deleted

Raises:



41
42
43
44
45
46
47
48
49
50
# File 'lib/ptero/generators/routesgenerator.rb', line 41

def unroute(path)
  get_current_routes
  raise Ptero::Exception::GeneratorException, "No such route #{path}" unless @routes.has_key? path
  @routes.delete path
  Mute::IO.capture_stdout do
    reload
  end
  puts "UNROUTE - #{path}".red
  self
end