Module: Sinatra::Helpers

Defined in:
lib/sinatra/helpers.rb,
lib/sinatra/helpers/country.rb,
lib/sinatra/helpers/haml_error_presenter.rb

Defined Under Namespace

Modules: Country Classes: HamlErrorPresenter

Constant Summary collapse

VERSION =
"0.2.0"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.registered(app) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/sinatra/helpers.rb', line 14

def self.registered(app)
  app.set :default_year_loffset, -60 
  app.set :default_year_uoffset, 0
  app.set :default_month_names, Date::MONTHNAMES

  app.set :default_currency_unit, '$'
  app.set :default_currency_precision, 2
  app.set :default_currency_separator, ','
end

Instance Method Details

#country_choicesArray

Returns an array of pairs i.e.

  • “Afghanistan”, “AF”
  • “United States”, “US”
  • “Zimbabwe”, “ZW”

Returns:

  • (Array)

    the array of name, code pairs.



38
39
40
# File 'lib/sinatra/helpers.rb', line 38

def country_choices
  Country.to_select
end

#currency(number, opts = {}) ⇒ String?

Formats a number into a currency display. Uses the following settings:

  • settings.default_currency_unit (defaults to ‘$’)

  • settings.default_currency_precision (defaults to 2)

  • settings.default_currenty_separator (defaults to ‘,’)

Examples:


currency(100) == "$ 100.00"
# => true

currency(100, :unit => "£") == "£ 100.00"
# => true

currency(100, :precision => 0) == "$ 100"
=> # true

# somewhere in your sinatra context after registering Sinatra::Helpers
set :default_currency_unit, '£'
set :default_currency_precision, 3
set :default_currency_separator, ' '

currency(100) == "£ 100.000"
# => true

Parameters:

  • number (Numeric)

    the number you wish to display as a currency.

  • opts (Hash) (defaults to: {})

    the various options available.

Options Hash (opts):

  • :unit (#to_s) — default: defaults to '$'
  • :precision (Fixnum) — default: defaults to 2
  • :separator (#to_s) — default: defaults to ','

Returns:

  • (String)

    the formatted string based on ‘number`.

  • (nil)

    if given nil or an empty string.



211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/sinatra/helpers.rb', line 211

def currency(number, opts = {})
  return if number.to_s.empty?

  unit      = opts[:unit]      || settings.default_currency_unit
  precision = opts[:precision] || settings.default_currency_precision
  separator = opts[:separator] || settings.default_currency_separator

  ret = "%s %.#{ Integer(precision) }f" % [unit, number]
  parts = ret.split('.')
  parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{separator}")
  parts.join('.')
end

#day_choicesArray

Returns an array of pairs i.e.

  • 1, 1
  • 2, 2
  • 31, 31

Returns:

  • (Array)

    the array of day, day pairs.



50
51
52
53
# File 'lib/sinatra/helpers.rb', line 50

def day_choices
  days = (1..31).to_a
  days.zip(days)
end

#errors_on(object, options = { :class => 'errors' }) {|Sinatra::Helpers::HamlErrorPresenter| ... } ⇒ Object

Presents errors on your form. Takes the explicit approach and assumes that for every form you have, the copy for the errors are important, instead of producing canned responses.

Allows you to do the following in your haml view:

Examples:


- errors_on @user do |e|
  - e.on [:email, :not_present], "We need your email address."
  - e.on [:password, :not_present], "You must specify a password."

# produces the following:
# <div class="errors">
#   <ul>
#     <li>We need your email address</li>
#     <li>You must specify a password.</li>
#   </ul>
# </div>

Parameters:

  • object (#errors)

    An object responding to #errors. This validation also checks for the presence of a #full_messages method in the errors object for compatibility with ActiveRecord style objects.

  • options (Hash) (defaults to: { :class => 'errors' })

    a hash of HTML attributes to place on the containing div.

Options Hash (options):

  • :class (#to_s) — default: defaults to errors

    The css class to put in the div.

Yields:

See Also:



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/sinatra/helpers.rb', line 161

def errors_on(object, options = { :class => 'errors' }, &block)
  return if object.errors.empty?

  lines = if object.errors.respond_to?(:full_messages)
    object.errors.full_messages
  else
    HamlErrorPresenter.new(object.errors).present(self, &block)
  end

  haml_tag(:div, options) do
    haml_tag(:ul) do
      lines.each do |error|
        haml_tag(:li, error)
      end
    end
  end
end

#h(str) ⇒ Object

Returns an HTML sanitized string.



25
26
27
# File 'lib/sinatra/helpers.rb', line 25

def h(str)
  Rack::Utils.escape_html(str)
end

#month_choices(month_names = settings.default_month_names) ⇒ Array

Returns an array of pairs i.e.

  • ‘January’, 1
  • ‘February’, 2
  • ‘December’, 12

You may pass in Date::ABBR_MONTHNAMES if you want the shortened month names.

Parameters:

  • month_names (Array) (defaults to: settings.default_month_names)

    (defaults to Date::MONTHNAMES) an array with the first element being nil, element 1 being January, etc.

Returns:

  • (Array)

    the array of month name, month pairs.



66
67
68
69
70
# File 'lib/sinatra/helpers.rb', line 66

def month_choices(month_names = settings.default_month_names)
  month_names.map.
    with_index { |month, idx| [month, idx] }.
    tap        { |arr| arr.shift }
end

#percentage(number, precision = 2) ⇒ String?

Show the percentage representation of a numeric value.

Examples:

percentage(100) == "100.00%"
percentage(100, 0) == "100%"

Parameters:

  • number (Numeric)

    A numeric value

  • precision (Fixnum) (defaults to: 2)

    (defaults to 2) Number of decimals to show.

Returns:

  • (String)

    the number displayed as a percentage

  • (nil)

    given a nil value or an empty string.



234
235
236
237
238
239
# File 'lib/sinatra/helpers.rb', line 234

def percentage(number, precision = 2)
  return if number.to_s.empty?

  ret = "%02.#{ precision }f%" % number
  ret.gsub(/\.0*%$/, '%')
end

#select_options(pairs, current = nil, prompt = nil) ⇒ Object

Accepts a list of pairs and produces option tags.

Examples:


select_options([['One', 1], ['Two', 2]])
select_options([['One', 1], ['Two', 2]], 1)
select_options([['One', 1], ['Two', 2]], 1, '- Choose -')

# using it with the provided date helpers...
select_options year_choices, 2010 # select 2010 as default
select_options month_choices, 5 # select May as default
select_options day_choices, 25 # select the 25th as default

Parameters:

  • pairs (Array)

    a collection of label, value tuples.

  • current (Object) (defaults to: nil)

    the current value of this select.

  • prompt (#to_s) (defaults to: nil)

    a default prompt to place at the beginning of the list.



122
123
124
125
126
127
128
# File 'lib/sinatra/helpers.rb', line 122

def select_options(pairs, current = nil, prompt = nil)
  pairs.unshift([prompt, '']) if prompt

  pairs.map { |label, value|
    tag(:option, label, :value => value, :selected => (current == value))
  }.join("\n")
end

#year_choices(loffset = settings.default_year_loffset, uoffset = settings.default_year_uoffset) ⇒ Array

Returns an array of pairs i.e.

  • 2005, 2005
  • 2006, 2006
  • 2010, 2010

Examples:


year_choices # assuming it's now 2010
# => [[1950, 1950], ..., [2010, 2010]]

# we can pass in options
year_choices(0, 6) # like for credit card options
# => [[2010, 2010], ..., [2016, 2016]]

# also we can override settings at the app level
set :default_year_loffset, 0
set :default_year_uoffset, 6
year_choices
# => [[2010, 2010], ..., [2016, 2016]]

Parameters:

  • loffset (Fixnum) (defaults to: settings.default_year_loffset)

    (defaults to -60) The lower offset relative to the current year. If it’s 2010 now, passing in -5 here will start the year list at 2005 for example.

  • uoffset (Fixnum) (defaults to: settings.default_year_uoffset)

    (defaults to 0) The upper offset relative to the current year. If it’s 2010 now, passing in 5 or +5 here will end the year list at 2015 for example.

Returns:

  • (Array)

    the array of year, year pairs.



100
101
102
103
# File 'lib/sinatra/helpers.rb', line 100

def year_choices(loffset = settings.default_year_loffset, uoffset = settings.default_year_uoffset)
  years = ((Date.today.year + loffset)..(Date.today.year + uoffset)).to_a
  years.zip(years)
end