Module: Padrino::Routing::ClassMethods

### Home Classes Methods

### In Files

- lib/padrino-core/application/routing.rb

### Methods

- #add_filter
- #after
- #before
- #compiled_router
- #construct_filter
- #controller
- #controllers
- #deferred_routes
- #get
- #parent
- #recognize_path
- #reset_router!
- #router
- #url
- #url_for
- #urls

### Files

- README.rdoc

### Class/Module Index

Quicksearch

- Padrino
- Padrino::Application
- Padrino::ApplicationLoadError
- Padrino::ApplicationSetupError
- Padrino::Cli
- Padrino::Cli::Adapter
- Padrino::Cli::Base
- Padrino::Erubis
- Padrino::Erubis::SafeBufferEnhancer
- Padrino::Erubis::SafeBufferTemplate
- Padrino::Erubis::Template
- Padrino::Filter
- Padrino::Flash
- Padrino::Flash::Helpers
- Padrino::Flash::Storage
- Padrino::Logger
- Padrino::Logger::Colorize
- Padrino::Logger::Extensions
- Padrino::Logger::Rack
- Padrino::Module
- Padrino::Mounter
- Padrino::Mounter::MounterException
- Padrino::Reloader
- Padrino::Reloader::Rack
- Padrino::Rendering
- Padrino::Rendering::ClassMethods
- Padrino::Rendering::InstanceMethods
- Padrino::Rendering::SafeTemplate
- Padrino::Rendering::TemplateNotFound
- Padrino::Router
- Padrino::Routing
- Padrino::Routing::ClassMethods
- Padrino::Routing::InstanceMethods
- Padrino::Routing::Parent
- Padrino::Routing::UnrecognizedException
- Padrino::Server
- Padrino::ShowExceptions
- Padrino::Tasks
- Padrino::Utils
- HttpRouter
- HttpRouter::Node
- HttpRouter::Node::Path
- HttpRouter::Request
- HttpRouter::Route
- Haml
- Haml::Helpers
- Haml::Util
- Sinatra
- Sinatra::Request
- Slim
- Slim::Template
- Tilt
- Tilt::HamlTemplate
- FileSet
- Kernel
- Module
- Object
- ObjectSpace
- PadrinoTasks
- String
- SupportLite

No matching classes.

# Padrino::Routing::ClassMethods

Class methods responsible for enhanced routing for controllers.

### Public Instance Methods

add_filter(type, &block) click to toggle source

Adds a filter hook to a request.

    # File lib/padrino-core/application/routing.rb, line 387
    def  add_filter(type, &block)
      filters[type] << block
    end

after(*args, &block) click to toggle source

Add an after filter hook

@see construct_filter

    # File lib/padrino-core/application/routing.rb, line 380
    def after(*args, &block)
      add_filter :after, &(args.empty? ? block : construct_filter(*args, &block))
    end

before(*args, &block) click to toggle source

Add a before filter hook

@see construct_filter

    # File lib/padrino-core/application/routing.rb, line 371
    def before(*args, &block)
      add_filter :before, &(args.empty? ? block : construct_filter(*args, &block))
    end

compiled_router() click to toggle source

Compiles the routes including deferred routes.

    # File lib/padrino-core/application/routing.rb, line 487
    def compiled_router
      if deferred_routes.empty?
        router
      else
        deferred_routes.each { |_, routes| routes.each { |(route, dest)| route.to(dest) } }
        @deferred_routes = nil
        router.sort!
        router
      end
    end

construct_filter(*args, &block) click to toggle source

Creates a filter to process before/after the matching route.

@param [Array] args

@example We are be able to filter with String path

    before('/') { 'only to :index' }
    get(:index} { 'foo' } # => filter match only before this.
    get(:main) { 'bar' }

@example is the same of

    before(:index) { 'only to :index' }
    get(:index} { 'foo' } # => filter match only before this.
    get(:main) { 'bar' }

@example it works only for the given controller

    controller :foo do
      before(:index) { 'only to for :foo_index' }
      get(:index} { 'foo' } # => filter match only before this.
      get(:main) { 'bar' }
    end

    controller :bar do
      before(:index) { 'only to for :bar_index' }
      get(:index} { 'foo' } # => filter match only before this.
      get(:main) { 'bar' }
    end

@example if filters based on a symbol or regexp

    before :index, /main/ do; ... end
    # => match only path that are  +/+ or contains +main+

@example filtering everything except an occurency

    before :except => :index do; ...; end

@example you can also filter using a request param

    before :agent => /IE/ do; ...; end
    # => match +HTTP_USER_AGENT+ containing +IE+

@see www.padrinorb.com/guides/controllers#route-filters

    # File lib/padrino-core/application/routing.rb, line 432
    def construct_filter(*args, &block)
      options = args.last.is_a?(Hash) ? args.pop : {}
      except = options.key?(:except) && Array(options.delete(:except))
      raise("You cannot use except with other options specified") if except && (!args.empty? || !options.empty?)
      options = except.last.is_a?(Hash) ? except.pop : {} if except
      Filter.new(!except, @_controller, options, Array(except || args), &block)
    end

controller(*args, &block) click to toggle source

Method to organize our routes in a better way.

@param [Array] args

    Controller arguments.

@yield []

    The given block will be used to define the routes within the
    Controller.

@example

    controller :admin do
      get :index do; ...; end
      get :show, :with => :id  do; ...; end
    end

    url(:admin_index) # => "/admin"
    url(:admin_show, :id => 1) # "/admin/show/1"

@example Using named routes follow the sinatra way:

    controller "/admin" do
      get "/index" do; ...; end
      get "/show/:id" do; ...; end
    end

@example Supply `:provides` to all controller routes:

    controller :provides => [:html, :xml, :json] do
      get :index do; "respond to html, xml and json"; end
      post :index do; "respond to html, xml and json"; end
      get :foo do; "respond to html, xml and json"; end
    end

@example Specify parent resources in padrino with the `:parent` option on the controller:

    controllers :product, :parent => :user do
      get :index do
        # url is generated as "/user/#{params[:user_id]}/product"
        # url_for(:product, :index, :user_id => 5) => "/user/5/product"
      end
      get :show, :with => :id do
        # url is generated as "/user/#{params[:user_id]}/product/show/#{params[:id]}"
        # url_for(:product, :show, :user_id => 5, :id => 10) => "/user/5/product/show/10"
      end
    end

@example Specify conditions to run for all routes:

    controller :conditions => {:protect => true} do
      def self.protect(protected)
        condition do
          halt 403, "No secrets for you!" unless params[:key] == "s3cr3t"
        end if protected
      end

      # This route will only return "secret stuff" if the user goes to
      # `/private?key=s3cr3t`.
      get("/private") { "secret stuff" }

      # And this one, too!
      get("/also-private") { "secret stuff" }

      # But you can override the conditions for each route as needed.
      # This route will be publicly accessible without providing the
      # secret key.
      get :index, :protect => false do
        "Welcome!"
      end
    end

@example Supply default values:

    controller :lang => :de do
      get :index, :map => "/:lang" do; "params[:lang] == :de"; end
    end

In a controller, before and after filters are scoped and don't affect other controllers or the main app. In a controller, layouts are scoped and don't affect other controllers or the main app.

@example

    controller :posts do
      layout :post
      before { foo }
      after  { bar }
    end

    # File lib/padrino-core/application/routing.rb, line 332
    def controller(*args, &block)
      if block_given?
        options = args.extract_options!

        # Controller defaults
        @_controller, original_controller = args,                        @_controller
        @_parents,    original_parent     = options.delete(:parent),     @_parents
        @_provides,   original_provides   = options.delete(:provides),   @_provides
        @_use_format, original_use_format = options.delete(:use_format), @_use_format
        @_cache,      original_cache      = options.delete(:cache),      @_cache
        @_map,        original_map        = options.delete(:map),        @_map
        @_conditions, original_conditions = options.delete(:conditions), @_conditions
        @_defaults,   original_defaults   = options,                     @_defaults

        # Application defaults
        @filters,     original_filters    = { :before => @filters[:before].dup, :after => @filters[:after].dup }, @filters
        @layout,      original_layout     = nil, @layout

        instance_eval(&block)

        # Application defaults
        @filters        = original_filters
        @layout         = original_layout

        # Controller defaults
        @_controller, @_parents,  @_cache = original_controller, original_parent,   original_cache
        @_defaults,   @_provides, @_map   = original_defaults,   original_provides, original_map
        @_conditions, @_use_format        = original_conditions, original_use_format
      else
        include(*args) if extensions.any?
      end
    end

Also aliased as: controllers
controllers(*args, &block) click to toggle source
Alias for: controller
deferred_routes() click to toggle source

Returns all routes that were deferred based on their priority.

    # File lib/padrino-core/application/routing.rb, line 499
    def deferred_routes
      @deferred_routes ||= Hash[ROUTE_PRIORITY.values.sort.map{|p| [p, []]}]
    end

get(path, *args, &block) click to toggle source

    # File lib/padrino-core/application/routing.rb, line 573
    def get(path, *args, &block) # @private
      conditions = @conditions.dup
      route('GET', path, *args, &block)

      @conditions = conditions
      route('HEAD', path, *args, &block)
    end

parent(name, options={}) click to toggle source

Provides many parents with shallowing.

@param [Symbol] name

    The parent name.

@param [Hash] options

    Additional options.

@example

    controllers :product do
      parent :shop, :optional => true, :map => "/my/stand"
      parent :category, :optional => true
      get :show, :with => :id do
        # generated urls:
        #   "/product/show/#{params[:id]}"
        #   "/my/stand/#{params[:shop_id]}/product/show/#{params[:id]}"
        #   "/my/stand/#{params[:shop_id]}/category/#{params[:category_id]}/product/show/#{params[:id]}"
        # url_for(:product, :show, :id => 10) => "/product/show/10"
        # url_for(:product, :show, :shop_id => 5, :id => 10) => "/my/stand/5/product/show/10"
        # url_for(:product, :show, :shop_id => 5, :category_id => 1, :id => 10) => "/my/stand/5/category/1/product/show/10"
      end
    end

    # File lib/padrino-core/application/routing.rb, line 464
    def parent(name, options={})
      defaults = { :optional => false, :map => name.to_s }
      options = defaults.merge(options)
      @_parents = Array(@_parents) unless @_parents.is_a?(Array)
      @_parents << Parent.new(name, options)
    end

recognize_path(path) click to toggle source

Recognize a given path

@param [String] path

    Path+Query to parse

@return [Symbol, Hash]

    Returns controller and query params.

@example Giving a controller like:

    controller :foo do
      get :bar, :map => 'foo-bar-:id'; ...; end
    end

@example You should be able to reverse:

    MyApp.url(:foo_bar, :id => :mine)
    # => /foo-bar-mine

@example Into this:

    MyApp.recognize_path('foo-bar-mine')
    # => [:foo_bar, :id => :mine]

    # File lib/padrino-core/application/routing.rb, line 533
    def recognize_path(path)
      responses = @router.recognize(Rack::MockRequest.env_for(path))
      responses = responses[0] if responses[0].is_a?(Array)
      [responses[0].path.route.name, responses[0].params]
    end

reset_router!() click to toggle source

Resets the http router and all deferred routes.

    # File lib/padrino-core/application/routing.rb, line 506
    def reset_router!
      @deferred_routes = nil
      router.reset!
    end

router() click to toggle source

Using {HttpRouter}, for features and configurations.

@example

    router.add('/greedy/:greed')
    router.recognize('/simple')

@see github.com/joshbuddy/http_router

    # File lib/padrino-core/application/routing.rb, line 480
    def router
      @router ||= HttpRouter.new
      block_given? ? yield(@router) : @router
    end

Also aliased as: urls
url(*args) click to toggle source

Instance method for url generation.

@example

    url(:show, :id => 1)
    url(:show, :name => 'test', :id => 24)
    url(:show, 1)
    url(:controller_name, :show, :id => 21)
    url(:controller_show, :id => 29)

    # File lib/padrino-core/application/routing.rb, line 549
    def url(*args)
      params = args.extract_options!  # parameters is hash at end
      names, params_array = args.partition{|a| a.is_a?(Symbol)}
      name = names.join("_").to_sym    # route name is concatenated with underscores
      if params.is_a?(Hash)
        params[:format] = params[:format].to_s unless params[:format].nil?
        params = value_to_param(params)
      end
      url =
        if params_array.empty?
          compiled_router.path(name, params)
        else
          compiled_router.path(name, *(params_array << params))
        end
      url[0,0] = conform_uri(uri_root) if defined?(uri_root)
      url[0,0] = conform_uri(ENV['RACK_BASE_URI']) if ENV['RACK_BASE_URI']
      url = "/" if url.blank?
      url
    rescue HttpRouter::InvalidRouteException
      route_error = "route mapping for url(#{name.inspect}) could not be found!"
      raise Padrino::Routing::UnrecognizedException.new(route_error)
    end

Also aliased as: url_for
url_for(*args) click to toggle source
Alias for: url
urls() click to toggle source
Alias for: router

[Validate]

Generated with the Darkfish Rdoc Generator 2.