-
Notifications
You must be signed in to change notification settings - Fork 0
Backend Training: View Helper
Nelson Lee edited this page Dec 1, 2017
·
2 revisions
🔖 helper
Next, the flash messages in the views aren't great since we have to define flashes for all different states from rails. e.g. alert, notice, error, success, and custom flash keys. Therefore, we should create a helper method that deal with this for us.
# app/helpers/application_helper.rb
module ApplicationHelper
def rails_route
"#{controller_name}-#{action_name}"
end
def flash_messages
flash.each do |type, msg|
concat(content_tag(:div, msg, class: "alert #{bs_class_for(type)}"))
end
nil
end
private
def bs_class_for(type)
{
success: 'alert-success',
error: 'alert-danger',
alert: 'alert-warning'
}[type.to_sym] || 'alert-info'
end
end
p.s. Here we are just mapping the bootstrap classes with the flash types provided by rails.
Let's apply it to the view
# app/views/contacts/new.slim
section.jumbotron[id='hero']
......
section[id='contact-info']
.container
......
.row
.col-md-5
p= t('.form.description')
= flash_messages
= simple_form_for @contact do |f|
= f.input :name,
label: false
= f.input :email,
label: false
= f.input :message,
label: false,
input_html: { rows: 5 }
= f.button :submit,
class: 'btn-primary'
.col-md-7
......
Try submitting the form again, and it should work like before.
Now, we know how to add helpers. Let's add helpers for phone, email, and address
# app/helpers/application_helper.rb
module ApplicationHelper
......
def phone_link(phone)
link_to phone, "tel:#{phone.gsub(/[^\d]/, '')}"
end
def email_link(email)
link_to t('.email'), "mailto:#{email}"
end
def address_link(address)
link_to address, "https://maps.google.com?q=#{address}", target: '_blank'
end
private
......
end
And change our translation files
# config/locales/en.yml
en:
......
contacts:
new:
email: Email Us
......
info:
contact:
title: Contact Information
phone: (778) 806-1108
email: dev@cleverbnana.com
address: 5050 Kingsway, Unit 412, Burnaby, BC, V5H4H2
......
Apply the helpers to the view.
# app/views/contacts/new.slim
section.jumbotron[id='hero']
......
section[id='contact-info']
.container
.row
......
.row
.col-md-5
......
.col-md-7
strong= t('.info.contact.title')
ul
li
= fa_icon('phone')
|
= phone_link(t('.info.contact.phone'))
li
= fa_icon('envelope')
|
= email_link(t('.info.contact.email'))
li
= fa_icon('map-marker')
|
= address_link(t('.info.contact.address'))
br/
strong= t('.info.hours.title')
p== t('.info.hours.body')
Make sure your url is on /contacts/new
. Refresh the browser Command ⌘+r, and the end result should look like....
Great! Let's commit and move on...
$ git add -A
$ git commit -m 'View Helper'