Add menu helper

master
Guillaume Dott 2015-10-30 12:56:44 +01:00
parent 5abef4cef7
commit 728ea6b3ee
3 changed files with 66 additions and 0 deletions

View File

@ -1,3 +1,4 @@
require 'librarix/menu'
require 'librarix/the_movie_db'
require 'sinatra/base'
@ -10,7 +11,15 @@ require 'themoviedb'
module Librarix
class Application < Sinatra::Application
def initialize(app = nil)
super
Librarix::Menu.menu.add 'Home', '/'
Librarix::Menu.menu.add 'Add a movie', '/search'
end
helpers Librarix::TheMovieDB
helpers Librarix::Menu::Helper
get '/' do
slim :index, locals: {movies: Librarix::Redis::Movie.all.sort_by(&:release_date).reverse}

View File

@ -0,0 +1,56 @@
module Librarix
class Menu
module Helper
def menu
Librarix::Menu.menu.render request.path_info
end
end
def self.menu
@menu ||= new
end
attr_accessor :menu
def initialize
self.menu = []
end
def add(name, url)
self.menu << Element.new(name, url)
end
def render(path = nil)
around menu.map { |elem| elem.render path }.join
end
private
def around(content)
"<ul>#{content}</ul>"
end
class Element
attr_accessor :name, :url
def initialize(name, url)
self.name = name
self.url = url
end
def render(path = nil)
around "<a href=\"#{url}\">#{name}</a>", path: path
end
def current?(path)
path == url
end
private
def around(element, path: nil)
"<li#{current?(path) ? ' class="active"' : ''}>#{element}</li>"
end
end
end
end

View File

@ -7,4 +7,5 @@ html
link rel="stylesheet" media="all" href="/application.css"
script type="text/javascript" src="/application.js"
body
== menu
== yield