LoginSignup
19
13

More than 5 years have passed since last update.

RailsのURLヘルパーをJSからrequireできるようにする

Last updated at Posted at 2016-06-25

RailsでJavaScriptをふんだんに使ったアプリケーションを書いていると、JavaScriptでURLを組み立てる必要がでてくることがあります。しかし、文字列でハードコーディングしてしまうと万が一将来的にパスが変わったときに追従が大変。

最近だと browserify-rails を使っていることも多いので、JavaScriptから必要な関数だけを require できるようにしたいです。

js_rails_routes

というわけでそこら辺の問題を解決する yuku-t/js_rails_routes を作りました。

インストール

Gemfile
gem 'js_rails_routes', group: :development

使い方

gemを追加したら自動的に "js:routes" というRakeタスクが追加されるのでそれを実行するだけです。

rake js:routes

すると "app/assets/javascripts/rails-routes.js" というファイルが作られます。

config/routes.rb
# == Route Map
#
#       Prefix Verb   URI Pattern                  Controller#Action
#     articles GET    /articles(.:format)          articles#index
#              POST   /articles(.:format)          articles#create
#  new_article GET    /articles/new(.:format)      articles#new
# edit_article GET    /articles/:id/edit(.:format) articles#edit
#      article GET    /articles/:id(.:format)      articles#show
#              PATCH  /articles/:id(.:format)      articles#update
#              PUT    /articles/:id(.:format)      articles#update
#              DELETE /articles/:id(.:format)      articles#destroy
Rails.application.routes.draw do
  resources :articles
end

このようなルーティングを持っている場合、こんなファイルが生成されます。

app/assets/javascripts/rails-routes.js
// Don't edit manually. `rake js:routes` generates this file.
export function article_path(params) { return '/articles/' + params.id + ''; }
export function articles_path(params) { return '/articles'; }
export function edit_article_path(params) { return '/articles/' + params.id + '/edit'; }
export function new_article_path(params) { return '/articles/new'; }

あとはいつものように require するだけですね。

参考

  • railsware/js-routes

    同じ問題を解決するgemですが、sprocketsを使うことを前提としており、出力されたルーティング関数をグローバルに定義された Routes オブジェクトのプロパティになります。

  • mtrpcic/js-routes

    sprockets非依存でファイルを書き出すrakeタスク。これもグローバル経由になる。最初 @mizchi がこれを雑に改造して require 可能にしたものを、いろいろと整備して拡張してrubygemsに公開したのが js_rails_routes

19
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
13