簡體   English   中英

從Rails路線創建ruby哈希對象?

[英]Creating ruby hash object from Rails routes?

使用rails 4.2.1

我想將聲明從config/routes.rb rails聲明的路由存儲到可以訪問或渲染的ruby哈希中。

哈希應采用以下格式

{
  name: 'path',
  # e.g.
  login: '/login',
  home: '/'
}

如何在rails執行此操作?

注:我想你打通路線Rails.application.routes ,也許名字從Rails.application.routes.routes.named_routes.keys ,但下一步是什么?

如果確實需要這樣做,則可以:

ri = ActionDispatch::Routing::RoutesInspector.new([])
result = ri.send :collect_routes, Rails.application.routes.routes

結果將是一系列散列,如下所示:

{:name=>"product", :verb=>"GET", :path=>"/products/:id(.:format)", :reqs=>"products#show", :regexp=>"^\\/products\\/([^\\/.?]+)(?:\\.([^\\/.?]+))?$"}

這將為您提供一個哈希值,其中鍵是路由名稱,值是路徑:

routes = Hash[Rails.application.routes.routes.map { |r| [r.name, r.path.spec.to_s] }]

routes現在看起來像:

{
  "entities" => "/entities(.:format)",
  "new_entity" => "/entities/new(.:format)",
  "edit_entity" => "/entities/:id/edit(.:format)",
  "entity" => "/entities/:id(.:format)"
}

您可能希望使用JS-Routes gem生成一個javascript文件,該文件將所有名為Rails的路由定義為javascript助手。

設置(只需將其添加到資產管道):

# add to your application.js
/*
= require js-routes
*/

使用您的JavaScript代碼,如下所示:

Routes.users_path()                   // => "/users"
Routes.user_path(1)                   // => "/users/1"
Routes.user_path(1, {format: 'json'}) // => "/users/1.json"

在此處找到文檔: https : //github.com/railsware/js-routes#usage

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM