Last active
December 17, 2015 05:49
-
-
Save dalpo/5561028 to your computer and use it in GitHub Desktop.
Cancan link Helper
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
module CancanLinkHelper | |
def show_link(*args, &block) | |
if block_given? && can?(:read, args[0]) | |
object = args[0] | |
html_options = args[1] || {} | |
show_link(object, capture(&block), html_options) | |
elsif can?(:read, args[0]) | |
object = args[0] | |
content = args[1] || glyph(:eye_open) | |
html_options = args[2] || {} | |
url = html_options[:url] || object | |
link_to(content, url, html_options) | |
end | |
end | |
def edit_link(*args, &block) | |
if block_given? && can?(:update, args[0]) | |
object = args[0] | |
html_options = args[1] || {} | |
edit_link(object, capture(&block), html_options) | |
elsif can?(:update, args[0]) | |
object = args[0] | |
content = args[1] || glyph(:pencil) | |
html_options = args[2] || {} | |
url = html_options[:url] || [:edit, object].flatten | |
link_to(content, url, html_options) | |
end | |
end | |
def destroy_link(*args, &block) | |
if block_given? && can?(:destroy, args[0]) | |
object = args[0] | |
html_options = args[1] || {} | |
destroy_link(object, capture(&block), html_options) | |
elsif can?(:destroy, args[0]) | |
object = args[0] | |
content = args[1] || glyph(:remove) | |
html_options = args[2] || {} | |
url = html_options[:url] || object | |
link_to(content, url, html_options.merge(method: :delete, confirm: t('actions.confirm'))) | |
end | |
end | |
def create_link(*args, &block) | |
if block_given? && can?(:create, args[0]) | |
object = args[0] | |
html_options = args[1] || {} | |
create_link(object, capture(&block), html_options) | |
elsif can?(:create, args[0]) | |
object = args[0] | |
content = args[1] || glyph(:plus) | |
html_options = args[2] || {} | |
if object.kind_of? Array | |
object_array = object | |
object = object_array.pop | |
object_class = (object.kind_of?(Class) ? object : object.class) | |
url = html_options[:url] || ([:new] + object_array + [object_class.name.underscore.to_sym]) | |
else | |
object_class = (object.kind_of?(Class) ? object : object.class) | |
url = html_options[:url] || [:new, object_class.name.underscore.to_sym] | |
end | |
link_to(content, url, html_options) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment