Created
August 26, 2015 12:23
-
-
Save tkawa/08744ab6a3136de33680 to your computer and use it in GitHub Desktop.
Rails 1レコードで複数のURLパラメータを埋めるためのパッチ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 1レコードで複数のURLパラメータを埋めるためのパッチ | |
# /users/1/posts/2 のとき Post モデルに additional_path_args を以下のように定義すれば | |
# url_for(post) や link_to post と書けるようになる。 | |
# def additional_path_args | |
# user | |
# end | |
module HelperMethodBuilderExt | |
def handle_model(record) | |
named_route, args = super | |
[named_route, expand_args(args, record)] | |
end | |
def handle_list(list) | |
named_route, args = super | |
[named_route, expand_args(args, list.last)] | |
end | |
private | |
def expand_args(args, record = nil) | |
args = expand_last_arg(args, record) | |
args.inject([]) do |result, arg| | |
if !arg.is_a?(Symbol) && !arg.is_a?(String) && !arg.is_a?(Class) | |
model = arg.to_model | |
if model.respond_to?(:additional_path_args) | |
result.push(*Array(model.additional_path_args)) | |
end | |
end | |
result << arg | |
end | |
end | |
def expand_last_arg(args, record) | |
if !record.nil? && !record.is_a?(Symbol) && !record.is_a?(String) && !record.is_a?(Class) | |
model = record.to_model | |
if !model.persisted? && model.respond_to?(:additional_path_args) | |
args += Array(model.additional_path_args) | |
end | |
end | |
args | |
end | |
end | |
ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.send(:prepend, HelperMethodBuilderExt) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment