Skip to content

Instantly share code, notes, and snippets.

@elvisgiv
Last active March 3, 2016 11:06
Show Gist options
  • Save elvisgiv/1318ae31164b9e40baef to your computer and use it in GitHub Desktop.
Save elvisgiv/1318ae31164b9e40baef to your computer and use it in GitHub Desktop.

Sanitize url

in ../Gemfile

# for sanitize URL
gem 'babosa'

https://github.com/norman/babosa

in ../config/routes.rb

  ...
  # qa_questions
  resources :qa_questions, except: :show
  get '/question/:id/(:name)', to: 'qa_questions#show', as: 'showquestion'
  ...

in ../app/models/question.rb

  ...
  before_validation :_before_validate

  def _before_validate
    self.name = self.title.to_slug.normalize.transliterate(:russian).to_s
  end
  ...

in _../app/controllers/qa_questions_controller.rb

  ...
  def index
    @items = Question.all
  end
  ...

in ../app/views/qa_questions/index.html.haml

  ...
  - @items.each do |item|
    %h3= link_to item.title, showquestion_path(:id => item.id, name: item.name)
    = item.description.truncate(200)
  ...

.truncate(200) показывает первые 200 символов в сообщении

расшифровка кода)

####в routes.rb в записи get '/question/:id/(:name)':

:id - означает обязательный параметер

(:name) - означает НЕобязательный параметр

Например в браузере одна и таже страница может быть и с урлом /question/12/pirotehnika_nasha и с урлом /question/12

####в question.rb отрабатывакт колбэк before_validation, который срабатывает ПЕРЕД сохранением записи в базу данных.

Это необходимо в случае валидации какого-либо поля (например поле может стать обязательным, но в форме оно не заполняется(наш случай)).

запись self.name = self.title.to_slug.normalize.transliterate(:russian).to_s присваивает полю name в базе данных значение поля title(которое приходит из формы) с методами, которые дает нам гем babosa для красивого отображения названия в урле (:name)

Sanitize HTML, replace end lines with BR

view:

= nl2br(sanitize(message.message, tags: [])).html_safe

controller:

= nl2br(ActionView::Base.full_sanitizer.sanitize(message.message)).html_safe

helper:

# app/helpers/message_helper.rb

  def nl2br(s)
    s.gsub(/\n/, '<br>')
  end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment