Skip to content

Commit

Permalink
Merb style url generator for named and resource routes in controllers.
Browse files Browse the repository at this point in the history
  • Loading branch information
Eivind Uggedal committed Apr 11, 2008
1 parent aeccde7 commit 0e427b4
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
26 changes: 26 additions & 0 deletions lib/halcyon/controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,32 @@ def not_found(body='Not Found')
{:status => 404, :body => body}
end
alias_method :missing, :not_found

# Returns the name of the controller in path form.
def self.controller_name
@controller_name ||= self.name.to_const_path
end

# Returns the name of the controller in path form.
def controller_name
self.class.controller_name
end

# Generates a URL based on the given name and passed
# options. Used with named routes and resources:
#
# url(:users) # => "/users"
# url(:admin_permissons) # => "/admin/permissions"
# url(:user, @user) # => "/users/1"
#
# Based on the identical method of Merb's controller.
def url(name, rparams={})
Halcyon::Application::Router.generate(name, rparams,
{ :controller => controller_name,
:action => method
}
)
end

end

Expand Down
14 changes: 14 additions & 0 deletions spec/halcyon/controller_spec.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require 'ostruct'

describe "Halcyon::Controller" do

before do
Expand Down Expand Up @@ -52,5 +54,17 @@
controller = Specs.new(Rack::MockRequest.env_for(""))
controller.uri.should == '/'
end

it 'should provide url accessor for resource index route' do
controller = Resources.new(Rack::MockRequest.env_for("/resources"))
controller.uri.should == controller.url(:resources)
end

it 'should provide url accessor for resource show route' do
resource = Model.new
resource.id = 1
controller = Resources.new(Rack::MockRequest.env_for("/resources/1"))
controller.uri.should == controller.url(:resource, resource)
end

end
4 changes: 4 additions & 0 deletions spec/spec_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ def show
end
end

class Model
attr_accessor :id
end

class Halcyon::Application
route do |r|
r.resources :resources
Expand Down

0 comments on commit 0e427b4

Please sign in to comment.