Last active
December 17, 2015 08:29
-
-
Save slant/5580831 to your computer and use it in GitHub Desktop.
Dynamic route generation in Rails
This file contains hidden or 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
# Without the extra stuff | |
# Helper | |
class Helper | |
def edit_resource_link(text, resource, &block) | |
#if CanCan blah blah | |
content_tag(:a, text, send(:"edit_#{resource.class.name.downcase}_path", resource), &block) | |
#end | |
end | |
end | |
# View | |
<%= edit_resource_link("Edit Post", @post) %> | |
# If authorized | |
# => <a href="/posts/1/edit">Edit Post</a> | |
# If not authorized | |
# => |
This file contains hidden or 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
# This does actually produce an anchor tag | |
class Helper | |
# stubbing this as Rails provides it | |
def edit_post_path(text, resource, &block) | |
"/#{resource.class.name.downcase}s/1/edit" | |
end | |
def edit_resource_link(text, resource, &block) | |
# You would use `content_tag(:a, text, send(...))` | |
'<a href="' + | |
send(:"edit_#{resource.class.name.downcase}_path", resource) + | |
'">' + text + '</a>' | |
# you may even want to extract the concatination of the _path method name to yet another helper method | |
end | |
end | |
class Post; end | |
@post = Post.new | |
# You would use this here: | |
# <%= edit_resource_link("Edit Post", @post) %> | |
puts Helper.new.edit_resource_link("Edit Post", @post) | |
# => <a href="/posts/1/edit">Edit Post</a> | |
# http://apidock.com/rails/ActionView/Helpers/TagHelper/content_tag | |
#content_tag(:a, text, send(:"edit_#{resource.class.name.downcase}_path", resource), &block) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment