Reputation: 117
I attempted to use the sinatra-flash gem with my application and get an "undefined local variable or method 'flash'" error when I try to run it.
my_app:
require 'sinatra/base'
require 'sinatra/flash'
class GGInfraUserManager < Sinatra::Base
enable :sessions
register Sinatra::Flash
...(rest of app)
post '/' do
flash[:error] = "Password must be a minimum of 8 characters" unless new_password.match /.{8}/
log.info "#{Time.now} password meets policy requirements"
end
redirect '/'
end
In my erb view file (at the top):
<div id="flash" class="notice">
<a class="close" data-dismiss="alert">×</a>
<%= flash.now[:error] %>
</div>
Can someone please tell me how to correct this error so that the flash functionality will work?
Upvotes: 1
Views: 1146
Reputation: 8478
While the gem seems comfortable enough to use why not implement it yourself. It's in fact just a couple of lines:
#in your app.rb:
helpers do
#a partial helper
def partial(template, locals = {})
slim template, :layout => false, :locals => locals
end
#the flash helper
def flash
@flash = session.delete(:flash)
end
end
get '/' do
session[:flash] = ["Some happy news", "alert-success"]
end
Then you can add a partial view which I called partial_flash.slim
-if flash
-message, status = @flash
.alert class=(status) = message
You call that partial usually from your layout file or any other view that needs a flash message:
==partial :partial_flash
So a route is called, the layout is loaded and checks if flash
. If there is, it displays a flash message with a specified class. I use Twitter Bootstrap, so alert-success
is a green message box.
You can see an example app here: https://github.com/burningTyger/farhang-app
Upvotes: 3