O Ruby on Rails possui o métogo strip_tags para remover tags html. Esse método está apenas disponível na camada de view, uma vez que faz parte ActionView::Helpers::SanitizeHelper.
Eu não concordo com essa implementação do Rails, acho que deveria ser disponível também na camada de controller e model, onde são os lugares que esse método é mais útil.
Para implementar o strip_tags nos controllers, models e libs, nós podemos adicionar esse método na classe String, desta forma estará disponível em qualquer lugar.
Abra o arquivo config/initializers/new_rails_defaults.rb:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | # Be sure to restart your server when you modify this file. # These settings change the behavior of Rails 2 apps and will be defaults # for Rails 3. You can remove this initializer when Rails 3 is released. if defined?(ActiveRecord) # Include Active Record class name as root for JSON serialized output. ActiveRecord::Base.include_root_in_json = true # Store the full class name (including module namespace) in STI type column. ActiveRecord::Base.store_full_sti_class = true end # Use ISO 8601 format for JSON serialized times and dates. ActiveSupport.use_standard_json_time_format = true # Don't escape HTML entities in JSON, leave that for the #json_escape helper. # if you're including raw json in an HTML page. ActiveSupport.escape_html_entities_in_json = false |
Adicione no final do arquivo as linhas:
1 2 3 4 5 | class String def strip_tags ActionController::Base.helpers.strip_tags(self) end end |
As linhas acima criam o método strip_tags na classe String.
Ficando o arquivo completo assim:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | # Be sure to restart your server when you modify this file. # These settings change the behavior of Rails 2 apps and will be defaults # for Rails 3. You can remove this initializer when Rails 3 is released. if defined?(ActiveRecord) # Include Active Record class name as root for JSON serialized output. ActiveRecord::Base.include_root_in_json = true # Store the full class name (including module namespace) in STI type column. ActiveRecord::Base.store_full_sti_class = true end # Use ISO 8601 format for JSON serialized times and dates. ActiveSupport.use_standard_json_time_format = true # Don't escape HTML entities in JSON, leave that for the #json_escape helper. # if you're including raw json in an HTML page. ActiveSupport.escape_html_entities_in_json = false class String def strip_tags ActionController::Base.helpers.strip_tags(self) end end |
Agora reinicie o seu servidor web para pegar essas novas configurações na inicialização da aplicação.
Agora quando você precisar do strip_tags pode usar assim, exemplos:
params['title'] = params['title'].strip_tags ou >> '<b>meu texto</b>'.strip_tags => "meu texto"
Se você gostou desse texto e acha que ajudou você, me recomende:
.



