Sinatra Bootstrap Starter / helpers / helpers.rb

helpers do
  include Rack::Utils
  alias_method :h, :escape_html
  
  # Convert a hash to a querystring for form population
  def hash_to_query_string(hash)
    hash.delete "password"
    hash.delete "password_confirmation"
    hash.collect {|k,v| "#{k}=#{v}"}.join("&")
  end

  # Redirect to last page or root
  def redirect_last
    if session[:redirect_to]
      redirect_url = session[:redirect_to]
      session[:redirect_to] = nil
      redirect redirect_url
    else
      redirect "/"
    end  
  end

  # Require login to view page
  def login_required
    if session[:user]
      return true
    else
      flash[:notice] =  "Login required to view this page"
      session[:redirect_to] = request.fullpath
      redirect "/login"
      return false
    end
  end

  # Require admin flag to view page
  def admin_required
    if current_user && is_admin?
      return true
    else
      flash[:notice] =  "Admin required to view this page"
      redirect "/"
      return false
    end
  end

  # Check user has admin flag
  def is_admin?
    !!current_user.admin?
  end

  # Check logged in user is the owner
  def is_owner? owner_id
    if current_user && current_user.id.to_i == owner_id.to_i
      return true
    else
      flash[:notice] =  "You are not authorised to view this page"
      redirect "/"
      return false
    end    
  end

  # Return current_user record if logged in
  def current_user
    return @current_user ||= User.first(:token => request.cookies["user"]) if request.cookies["user"]
    @current_user ||= User.first(:token => session[:user]) if session[:user]
  end

  # check if user is logged in?
  def logged_in?
    !!session[:user]
  end

  # Loads partial view into template. Required vriables into locals
  def partial(template, locals = {})
    erb(template, :layout => false, :locals => locals)
  end

  # string2md5 
  class String
    def to_md5
      Digest::MD5.hexdigest(self)
    end
  end

  def get_gravatar
    gravatar = []
    gravatar << "https://secure.gravatar.com/avatar/"
    gravatar << current_user.email.to_md5
    gravatar << "?s=140&d=http://todo.decimage.com/img/gravatar-user-420.png"
    gravatar.join
  end
  
end
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.