2 # This file is part of SMR.
4 # SMR is free software: you can redistribute it and/or modify it under the
5 # terms of the GNU General Public License as published by the Free Software
6 # Foundation, either version 3 of the License, or (at your option) any later
9 # SMR is distributed in the hope that it will be useful, but WITHOUT ANY
10 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
11 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License along with
14 # SMR. If not, see <http://www.gnu.org/licenses/>.
19 # Collection of helper methods for use in all views.
20 module ApplicationHelper
23 # Return date the user is currently browsing, as +Time+.
25 if session[:smr_browse_date].nil? then Time.new
26 else Time.at(session[:smr_browse_date]) end
30 # Returns change from +val1+ to +val2+ in percent, as smr_humanize()d String.
31 def percentage_change(val1, val2)
32 return nil if val1.zero? or val2.blank?
33 smr_humanize(Percentage.change(val1, val2))
37 # Returns percentage of +val+ from +base+, as smr_humanize()d String.
38 def percentage_of(base, val)
39 if base.zero? then return nil end
40 smr_humanize(BigDecimal(val.to_s).as_percentage_of(base))
44 # humanize a number in ways useful in SMR
50 # decide whether to round
51 skip_rounding = true if n.is_a?(Fixnum)
52 skip_rounding = true if (n.nil? or n == false)
54 if n.is_a?(Percentage)
56 format = if n.to_f < 10 then '%.1f' else '%i' end
61 format = '%s'+n.strftime('%Y-%m-%d')
66 # do generic rounding if necessary
69 when 0..1 then format = '%.4f'
70 when 1..9 then format = '%.3f'
71 when 10..99 then format = '%.2f'
72 when 100..1000 then format = '%.1f'
79 (format + '%s') % [n, unit]
84 # Returns menu to browse SMR functionality in HTML format, see
85 # @smr_menu_items and smr_menu_addsubitem().
86 # TODO: supports one sublevel only, do we ever need more?
88 content_tag(:ul, nil, :id=>'smr_menu') {
89 @smr_menu_items.reduce('') { |ctag, top|
90 if top.second.is_a?(Hash) then
92 ctag << content_tag(:li) do
93 link_to(top.first, top.second.delete('_toplink')) +
94 content_tag(:ul, nil) do
95 top.second.reduce('') { |c, sub|
96 c << content_tag(:li, link_to(sub.first, sub.second))
102 ctag << content_tag(:li, link_to(top.first, top.second))
109 # Provide link back to original object from SmrBlogItem. Returns nil if
110 # there is no reference on that item.
113 # - works only for +type=Comment+ right now and if the Comment is not
114 # older than 7 days (the later is intentional as we want to store THE
115 # TRUTH and not alternate it afterwards)
116 def smr_link_back(smr_blogitem, name)
117 raise 'smr_blogitem must be SmrBlogItem' unless smr_blogitem.is_a?(SmrBlogItem)
119 if smr_blogitem.type == 'Comment' and smr_blogitem.refid and smr_blogitem.date>7.days.ago then
120 link_to name, :controller=>:blog, :action=>:new, :id=>smr_blogitem.refid