module Rostra
module BaseHelper
# Method used to render to user names (e.g. where it says: "John Does says:"). You can,
# for example, use this method to turn "John Doe" into a link to his profile page.
#
def link_to_profile(user)
link_to user.rostra_user_name, main_app.user_path(user)
end
# Used to populate both the title and h1 elements for each page.
#
def page_title_helper
case "#{controller_name}##{action_name}"
when "questions#show" then @question.title
when "questions#index" then
if params[:tag_search].present?
"Recent Questions for tag #{params[:tag_search]}"
else
"Recent Questions"
end
when "questions#new" then "Post a new question"
when "questions#edit" then "Editing question"
when "answers#edit" then "Editing answer"
else "Recent Questions"
end
end
# Creates a list of tags linking to the index showing only questions with that tag
#
def tag_list(question)
tags = question.tags.map { |tag| link_to tag, questions_path(:tag_search => "#{tag}")}.join
content_tag :div, "Tags: #{tags}".html_safe, class: 'tags'
end
# Finds the url to the user's avatar following this logic:
#
# 1. Calls avatar on the user object
# 2. Uses the users email address to look for a gravatar
# 3. Renders app/assets/images/rostra/anonymous_avatar.png
#
def avatar_url(user)
if user.respond_to?(:avatar)
user.avatar
else
default_url = "#{main_app.root_url}assets/rostra/anonymous_avatar.png"
gravatar_id = Digest::MD5.hexdigest(user.rostra_user_email.downcase)
"http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}"
end
end
# Method to build links for ajax-y voting arrows.
#
def link_to_vote(direction, resource)
if user_signed_in? && ( (direction == :up && rostra_user.voted_for?(resource)) || (direction == :down && rostra_user.voted_against?(resource)) )
selected = 'selected'
else
selected = ''
end
link_to "Vote #{direction.capitalize}", vote_path(resource, direction), method: :put, remote: true, class: "vote #{direction} #{selected}"
end
# Returns a rostra object's base class name. For example, @question is an instance of
# Rostra::Question and so:
#
# class_name(@question) # => 'question'
#
def class_name(resource)
resource.class.name.split('::').last.downcase
end
private
def vote_path(resource, direction)
return '#' if !user_signed_in? || can?(:manage, resource)
if resource.is_a?(Rostra::Question)
vote_question_path(resource, vote_direction: direction)
else
vote_question_answer_path(resource.question, resource, vote_direction: direction)
end
end
end
end