From 728ea6b3eebab5049aec61a68a327931dfcf9507 Mon Sep 17 00:00:00 2001 From: Guillaume Dott Date: Fri, 30 Oct 2015 12:56:44 +0100 Subject: [PATCH] Add menu helper --- lib/librarix/application.rb | 9 ++++++ lib/librarix/menu.rb | 56 ++++++++++++++++++++++++++++++++++ lib/librarix/views/layout.slim | 1 + 3 files changed, 66 insertions(+) create mode 100644 lib/librarix/menu.rb diff --git a/lib/librarix/application.rb b/lib/librarix/application.rb index 519ec9c..3e7e086 100644 --- a/lib/librarix/application.rb +++ b/lib/librarix/application.rb @@ -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} diff --git a/lib/librarix/menu.rb b/lib/librarix/menu.rb new file mode 100644 index 0000000..d622da8 --- /dev/null +++ b/lib/librarix/menu.rb @@ -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) + "" + end + + class Element + attr_accessor :name, :url + + def initialize(name, url) + self.name = name + self.url = url + end + + def render(path = nil) + around "#{name}", path: path + end + + def current?(path) + path == url + end + + private + + def around(element, path: nil) + "#{element}" + end + end + end +end diff --git a/lib/librarix/views/layout.slim b/lib/librarix/views/layout.slim index f362a2b..eac0514 100644 --- a/lib/librarix/views/layout.slim +++ b/lib/librarix/views/layout.slim @@ -7,4 +7,5 @@ html link rel="stylesheet" media="all" href="/application.css" script type="text/javascript" src="/application.js" body + == menu == yield