Module: Sinatra::FormHelpers

Defined in:
lib/sinatra/form_helpers.rb

Defined Under Namespace

Classes: Fieldset

Instance Method Summary collapse

Instance Method Details

#button(value, options = {}) ⇒ Object

General purpose button, usually these need JavaScript hooks.


101
102
103
104
# File 'lib/sinatra/form_helpers.rb', line 101

def button(value, options={})
  single_tag :input, {:name => "button", :type => "button",
                      :value => value, :id => css_id('button', value)}.merge(options)
end

#checkbox(obj, field, values, options = {}) ⇒ Object

Form checkbox. Specify an array of values to get a checkbox group.


107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/sinatra/form_helpers.rb', line 107

def checkbox(obj, field, values, options={})
  join = options.delete(:join) || ' '
  labs = options.delete(:label)
  vals = param_or_default(obj, field, [])
  ary = values.is_a?(Array) && values.length > 1 ? '[]' : ''
  Array(values).collect do |val|
    id, text = id_and_text_from_value(val)
    single_tag(:input, options.merge(:type => "checkbox", :id => css_id(obj, field, id),
                                     :name => "#{obj}[#{field}]#{ary}", :value => id,
                                     :checked => vals.include?(id) ? 'checked' : nil)) +
    (labs.nil? || labs == true ? label(obj, "#{field}_#{id.to_s.downcase}", text) : '')
  end.join(join)
end

#css_id(*things) ⇒ Object


204
205
206
# File 'lib/sinatra/form_helpers.rb', line 204

def css_id(*things)
  things.compact.map{|t| t.to_s}.join('_').downcase.gsub(/\W/,'_')
end

#fast_escape_html(text) ⇒ Object


171
172
173
# File 'lib/sinatra/form_helpers.rb', line 171

def fast_escape_html(text)
  text.to_s.gsub(/\&/,'&amp;').gsub(/\"/,'&quot;').gsub(/>/,'&gt;').gsub(/</,'&lt;')
end

#fieldset(obj, legend = nil, &block) ⇒ Object

Raises:

  • (ArgumentError)

30
31
32
33
34
# File 'lib/sinatra/form_helpers.rb', line 30

def fieldset(obj, legend=nil, &block)
  raise ArgumentError, "Missing block to fieldset()" unless block_given?
  out = yield Fieldset.new(self, obj)
  '<fieldset>' + (legend.nil? ? '' : "<legend>#{fast_escape_html(legend)}</legend>") + out.to_s + '</fieldset>'
end

#form(action, method = :get, options = {}, &block) ⇒ Object

FormHelpers are a suite of helper methods built to make building forms in Sinatra a breeze.

link “jackhq”, “www.jackhq.com

label :person, :first_name input :person, :first_name textarea :person, :notes

etc.


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/sinatra/form_helpers.rb', line 14

def form(action, method=:get, options={}, &block)
  method_input = ''
  # the docs suggest using ':create', ':update', or ':delete'
  # but you can use any symbol for the method value
  # allows for more than 3 forms on a single page
  if method.is_a? Symbol      
    method_input = %Q(<input type="hidden" name="_method" value="#{method}" />)
    method = :post
  end
  action = "/#{action}" if action.is_a? Symbol

  out = tag(:form, nil, {:action => action, :method => method.to_s.upcase}.merge(options)) + method_input
  out << fieldset(action, &block) + '</form>' if block_given?
  out
end

#hash_to_html_attrs(options = {}) ⇒ Object


187
188
189
190
191
192
193
194
# File 'lib/sinatra/form_helpers.rb', line 187

def hash_to_html_attrs(options={})
  html_attrs = ""
  options.keys.sort.each do |key|
    next if options[key].nil? # do not include empty attributes
    html_attrs << %Q(#{key}="#{fast_escape_html(options[key])}" )
  end
  html_attrs.chop
end

#hidden(obj, field = nil, options = {}) ⇒ Object

Form hidden input. Specify value as :value => 'foo'


151
152
153
# File 'lib/sinatra/form_helpers.rb', line 151

def hidden(obj, field = nil, options = {})
  input(obj, field, options.merge(:type => 'hidden'))
end

#id_and_text_from_value(val) ⇒ Object


196
197
198
199
200
201
202
# File 'lib/sinatra/form_helpers.rb', line 196

def id_and_text_from_value(val)
  if val.is_a? Array
    [val.first, val.last]
  else
    [val, val]
  end
end

#image(src, options = {}) ⇒ Object

Link to an image


42
43
44
# File 'lib/sinatra/form_helpers.rb', line 42

def image(src, options={})
  single_tag :img, options.merge(:src => src)
end

#input(obj, field = nil, options = {}) ⇒ Object

Form text input. Specify the value as :value => 'foo'


52
53
54
55
56
57
58
59
60
# File 'lib/sinatra/form_helpers.rb', line 52

def input(obj, field=nil, options={})
  value = param_or_default(obj, field, options[:value])
  single_tag :input, options.merge(
    :type => options[:type] || "text",
    :id => css_id(obj, field),
    :name => field.nil? ? obj : "#{obj}[#{field}]",
    :value => value
  )
end

#label(obj, field, display = "", options = {}) ⇒ Object

Form field label


47
48
49
# File 'lib/sinatra/form_helpers.rb', line 47

def label(obj, field, display = "", options={})
  tag :label, (display.nil? || display == '') ? titleize(field.to_s) : display, options.merge(:for => css_id(obj, field))
end

Link to a URL


37
38
39
# File 'lib/sinatra/form_helpers.rb', line 37

def link(content, href=content, options={})
  tag :a, content, options.merge(:href => href)
end

#param_or_default(obj, field, default) ⇒ Object


179
180
181
182
183
184
185
# File 'lib/sinatra/form_helpers.rb', line 179

def param_or_default(obj, field, default)
  if field
    params[obj] ? params[obj][field.to_s] || default : default
  else
    params[obj] || default
  end
end

#password(obj, field = nil, options = {}) ⇒ Object

Form password input. Specify the value as :value => 'foo'


63
64
65
# File 'lib/sinatra/form_helpers.rb', line 63

def password(obj, field=nil, options={})
  input(obj, field, options.merge(:type => 'password'))
end

#radio(obj, field, values, options = {}) ⇒ Object

Form radio input. Specify an array of values to get a radio group.


122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/sinatra/form_helpers.rb', line 122

def radio(obj, field, values, options={})
  #content = @params[obj] && @params[obj][field.to_s] == value ? "true" : ""
  # , :checked => content
  join = options.delete(:join) || ' '
  labs = options.delete(:label)
  vals = param_or_default(obj, field, [])
  Array(values).collect do |val|
    id, text = id_and_text_from_value(val)
    single_tag(:input, options.merge(:type => "radio", :id => css_id(obj, field, id),
                                     :name => "#{obj}[#{field}]", :value => id,
                                     :checked => vals.include?(id) ? 'checked' : nil)) +
    (labs.nil? || labs == true ? label(obj, "#{field}_#{id.to_s.downcase}", text) : '')
  end.join(join)
end

#reset(value = 'Reset', options = {}) ⇒ Object

Form reset tag. Does anyone use these anymore?


95
96
97
98
# File 'lib/sinatra/form_helpers.rb', line 95

def reset(value='Reset', options={})
  single_tag :input, {:name => "reset", :type => "reset",
                      :value => value, :id => css_id('button', value)}.merge(options)
end

#select(obj, field, values, options = {}) ⇒ Object

Form select dropdown. Currently only single-select (not multi-select) is supported.


138
139
140
141
142
143
144
145
146
147
148
# File 'lib/sinatra/form_helpers.rb', line 138

def select(obj, field, values, options={})
  value = param_or_default(obj, field, options[:value])
  content = ""
  Array(values).each do |val|
    id, text = id_and_text_from_value(val)
    tag_options = { :value => id }
    tag_options[:selected] = 'selected' if id == value
    content << tag(:option, text, tag_options)
  end
  tag :select, content, options.merge(:id => css_id(obj, field), :name => "#{obj}[#{field}]")
end

#single_tag(name, options = {}) ⇒ Object

Standard single closing tags single_tag :img, :src => “images/google.jpg”

> <img src=“images/google.jpg” />


167
168
169
# File 'lib/sinatra/form_helpers.rb', line 167

def single_tag(name, options={})
  "<#{name.to_s} #{hash_to_html_attrs(options)} />"
end

#submit(value = 'Submit', options = {}) ⇒ Object

Form submit tag.


77
78
79
80
# File 'lib/sinatra/form_helpers.rb', line 77

def submit(value='Submit', options={})
  single_tag :input, {:name => "submit", :type => "submit",
                      :value => value, :id => css_id('button', value)}.merge(options)
end

#submit_with_post_icon(value = 'Submit', icon = '', options = {}) ⇒ Object

Form submit tag, with postfix icon.


89
90
91
92
# File 'lib/sinatra/form_helpers.rb', line 89

def submit_with_post_icon(value='Submit', icon='', options={})
  tag :button, "#{value} <i class='#{icon}'></i>", {:name => "submit", :type => "submit",
                                          :id => css_id('button', value)}.merge(options)
end

#submit_with_pre_icon(value = 'Submit', icon = '', options = {}) ⇒ Object

Form submit tag, with prefix icon.


83
84
85
86
# File 'lib/sinatra/form_helpers.rb', line 83

def submit_with_pre_icon(value='Submit', icon='', options={})
  tag :button, "<i class='#{icon}'></i> #{value}", {:name => "submit", :type => "submit",
                                          :id => css_id('button', value)}.merge(options)
end

#tag(name, content, options = {}) ⇒ Object

Standard open and close tags EX : tag :h1, “shizam”, :title => “shizam”

> <h1 title=“shizam”>shizam</h1>


158
159
160
161
162
# File 'lib/sinatra/form_helpers.rb', line 158

def tag(name, content, options={})
  "<#{name.to_s}" +
    (options.length > 0 ? " #{hash_to_html_attrs(options)}" : '') +
    (content.nil? ? '>' : ">#{content}</#{name}>")
end

#textarea(obj, field = nil, content = '', options = {}) ⇒ Object

Form textarea box.


68
69
70
71
72
73
74
# File 'lib/sinatra/form_helpers.rb', line 68

def textarea(obj, field=nil, content='', options={})
  content = param_or_default(obj, field, content)
  tag :textarea, content, options.merge(
    :id   => css_id(obj, field),
    :name => field.nil? ? obj : "#{obj}[#{field}]"
  )
end

#titleize(text) ⇒ Object


175
176
177
# File 'lib/sinatra/form_helpers.rb', line 175

def titleize(text)
  text.to_s.gsub(/_+/, ' ').gsub(/\b('?[a-z])/) { $1.capitalize }
end