Created
April 2, 2014 09:52
-
-
Save dalpo/9931185 to your computer and use it in GitHub Desktop.
Rails with Pundit policy 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 PolicyHelper | |
def can?(action, subject) | |
policy(subject).try "#{action}?" | |
end | |
def policy_helper_arguments(*args, &block) | |
object = args[0] | |
if block_given? | |
content = capture(&block) | |
html_options = args[1] || {} | |
elsif args.size.eql?(2) && args[1].kind_of?(Hash) | |
content = nil | |
html_options = args[1] || {} | |
else | |
content = args[1] | |
html_options = args[2] || {} | |
end | |
url = html_options[:url] | |
html_options.delete(:url) | |
html_options = {class: 'btn btn-mini'}.merge(html_options) if content.nil? | |
return object, content, url, html_options | |
end | |
def index_link(*args, &block) | |
object, content, url, html_options = policy_helper_arguments(*args, &block) | |
if can? :index, object | |
link_to (url || object.name.underscore.to_sym), html_options do | |
content || "#{glyph(:eye_open)} #{t('actions.show')}".html_safe | |
end | |
end | |
end | |
def show_link(*args, &block) | |
object, content, url, html_options = policy_helper_arguments(*args, &block) | |
if can? :show, object | |
link_to (url || object), html_options do | |
content || "#{glyph(:eye_open)} #{t('actions.show')}".html_safe | |
end | |
end | |
end | |
def new_link(*args, &block) | |
object, content, url, html_options = policy_helper_arguments(*args, &block) | |
if can? :new, object | |
link_to (url || [:new, object.name.underscore.to_sym]), html_options do | |
content || "#{glyph(:plus)} #{t('actions.new')}".html_safe | |
end | |
end | |
end | |
alias_method :create_link, :new_link | |
def edit_link(*args, &block) | |
object, content, url, html_options = policy_helper_arguments(*args, &block) | |
if can? :edit, object | |
link_to (url || [:edit, object]), html_options do | |
content || "#{glyph(:pencil)} #{t('actions.edit')}".html_safe | |
end | |
end | |
end | |
alias_method :update_link, :edit_link | |
def destroy_link(*args, &block) | |
object, content, url, html_options = policy_helper_arguments(*args, &block) | |
if can? :destroy, object | |
link_to (url || object), {method: :delete, confirm: t('actions.confirm')}.merge(html_options) do | |
content || "#{glyph(:times)} #{t('actions.delete')}".html_safe | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment