#103 Site Wide Announcements
Sometimes you need to display an administrative announcement to every page on the site and give the users the ability to hide the announcement. See how in this episode.
Update: as Simon pointed out in the comments, there's a problem with the announcement find conditions when passing a hide_time. The code below has been updated with the fix.
bash
script/generate scaffold announcement message:text starts_at:datetime ends_at:datetime
script/generate controller javascripts
script/generate scaffold announcement message:text starts_at:datetime ends_at:datetime script/generate controller javascripts
layouts/application.html.erb
<% unless current_announcements.empty? %>
<div id="announcement">
<% for announcement in current_announcements %>
<p><%=h announcement.message %></p>
<% end %>
<p><%= link_to_remote "Hide this message", :url => "/javascripts/hide_announcement.js" %></p>
</div>
<% end %>
<% unless current_announcements.empty? %> <div id="announcement"> <% for announcement in current_announcements %> <p><%=h announcement.message %></p> <% end %> <p><%= link_to_remote "Hide this message", :url => "/javascripts/hide_announcement.js" %></p> </div> <% end %>
models/announcement.rb
def self.current_announcements(hide_time)
with_scope :find => { :conditions => "starts_at <= now() AND ends_at >= now()" } do
if hide_time.nil?
find(:all)
else
find(:all, :conditions => ["updated_at > ? OR starts_at > ?", hide_time, hide_time])
end
end
end
def self.current_announcements(hide_time) with_scope :find => { :conditions => "starts_at <= now() AND ends_at >= now()" } do if hide_time.nil? find(:all) else find(:all, :conditions => ["updated_at > ? OR starts_at > ?", hide_time, hide_time]) end end end
application_helper.rb
def current_announcements
@current_announcements ||= Announcement.current_announcements(session[:announcement_hide_time])
end
def current_announcements @current_announcements ||= Announcement.current_announcements(session[:announcement_hide_time]) end
javascripts_controller.rb
def hide_announcement
session[:announcement_hide_time] = Time.now
end
def hide_announcement session[:announcement_hide_time] = Time.now end
hide_announcement.js.rjs
page[:announcement].hide
page[:announcement].hide
routes.rb
map.connect ":controller/:action.:format"
map.connect ":controller/:action.:format"
