• 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

I think that the complex Rails applications
such as maintained over years tend to have messy config/routes.
Today I'd like to introduce a simple way to keep them clean.

The way is really simple. Use with_options for each controller with prefix options.

rails>>
map.with_options(:controller => 'posts',
:name_prefix => 'posts_',
:path_prefix => 'posts') do |posts|

posts_rss_path => 'posts/rss'

posts.rss 'rss', :action => 'rss'
end
<<--

Still complex?
Okey, I have written the plugin for you.

With this plugin, you can draw the routes belonging to some controller like this.

rails>>
map.with_controller('posts') do |posts|
posts.rss # posts_rss_path => 'posts/rss'
end
<<--

As you can see, there's one more thing.
I have also installed MapperWithController class into RouteSet at this plugin for making named routes be completely DRY.

rails>>
class MapperWithController
def initialize(mapper)
@mapper = mapper
end

def method_missing(name, *args, &block)
path, *args = args
path ||= name.to_s
args.unshift path
@mapper.send name, *args, &block
end
end
<<--

map.namespace :posts does nearly same thing, but it couldn't be used for this purpose because of it is optimized to making namespaces for a routing.

posted by takiuchi takiuchi on Fri 14 Mar 2008 at 19:00 with 1 comment

ruby>>
map.resources :users
map.resource :session
<<--

routes.rbに出てくる、map.resource。綴り間違い??とひそかに思っていたらちゃんとありました。
map.resourceについてヘルプを見てみます。

Creates named routes for implementing verb-oriented controllers for
a singleton resource. A singleton resource is global to the current user visiting the application, such as a user‘s /account profile.

単数コントローラ名でパスを提供する場合に使えるようです。

  • a singular name is given to map.resource. The default controller name is taken from the singular name.
  • To specify a custom plural name, use the :plural option. There is no :singular option
  • No default index, new, or create routes are created for the singleton resource controller.
  • When nesting singleton resources, only the singular name is used as the path prefix (example: 'account/messages/1')
  • 単数形を使ったリソースを提供できます
  • :pluralオプションを使えば、複数を使うこともOK。:singularオプションはありません。
  • index, new, createのroutesは作られません
  • 入れ子で単数形resourceを使っている場合、prefixには単数形が使われます
    ex 'account/messages/1'

ヘルプにある生成されるというパスと私の環境のrake routesで表示されるパスが異なるようなので使用しているrailsで確認することが必要があるように思います。

posted by satoko satoko on Wed 28 Nov 2007 at 06:23 with 0 comments