Skip to content

Instantly share code, notes, and snippets.

@slant
Last active December 17, 2015 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slant/5580831 to your computer and use it in GitHub Desktop.
Save slant/5580831 to your computer and use it in GitHub Desktop.
Dynamic route generation in Rails
# 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 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