diff --git a/app/helpers/watchers_helper.rb b/app/helpers/watchers_helper.rb index ea26b5d966d5..27f883a66b93 100644 --- a/app/helpers/watchers_helper.rb +++ b/app/helpers/watchers_helper.rb @@ -30,26 +30,18 @@ module WatchersHelper # Create a link to watch/unwatch object # # * :replace - a string or array of strings with css selectors that will be updated, whenever the watcher status is changed - def watcher_link(object, user, options = { replace: ".watcher_link", class: "watcher_link" }) - options = options.with_indifferent_access - raise ArgumentError, "Missing :replace option in options hash" if options["replace"].blank? + def watcher_link(object, user, options = {}) + options = { replace: ".watcher_link", class: "watcher_link" }.merge(options) - return "" unless user&.logged? && object.respond_to?(:watched_by?) + return "" unless valid_watcher_conditions?(object, user, options) watched = object.watched_by?(user) - html_options = options - path = send(:"#{(watched ? 'unwatch' : 'watch')}_path", object_type: object.class.to_s.underscore.pluralize, - object_id: object.id, - replace: options.delete("replace")) - html_options[:class] = "#{html_options[:class]} button" + path = watcher_path(object, watched, options) - method = watched ? :delete : :post - - label = watched ? I18n.t(:button_unwatch) : I18n.t(:button_watch) + html_options = prepare_html_options(watched, options) - link_to(content_tag(:i, "", class: watched ? "button--icon icon-watched" : " button--icon icon-unwatched") + " " + - content_tag(:span, label, class: "button--text"), path, html_options.merge(method:)) + link_to_watcher_button(watched, path, html_options) end def watcher_button_arguments(object, user) @@ -77,4 +69,36 @@ def watcher_button_arguments(object, user) mobile_label: label } end + + private + + def valid_watcher_conditions?(object, user, options) + raise ArgumentError, "Missing :replace option in options hash" if options[:replace].blank? + + user&.logged? && object.respond_to?(:watched_by?) + end + + def watcher_path(object, watched, options) + action = watched ? "unwatch" : "watch" + send(:"#{action}_path", object_type: object.class.to_s.underscore.pluralize, object_id: object.id, replace: options[:replace]) + end + + def prepare_html_options(watched, options) + options.merge( + class: "#{options[:class]} button", + method: watched ? :delete : :post + ) + end + + def link_to_watcher_button(watched, path, html_options) + label = watched ? I18n.t(:button_unwatch) : I18n.t(:button_watch) + icon_class = watched ? "icon-watched" : "icon-unwatched" + + link_to( + content_tag(:i, "", class: "button--icon #{icon_class}") + + content_tag(:span, label, class: "button--text"), + path, + html_options + ) + end end