16 Rich Text Editing With Bootsy - getfretless/elevennote GitHub Wiki
The textarea in our note form is pretty sad looking. It's also being used to author HTML markup, a task for which a textarea is less than ideal. Let's address both of those shortcomings by including a gem called Bootsy.
Add Bootsy to your Gemfile and run bundle install
.
Gemfile
gem 'bootsy'
$ bundle install
Next, run Bootsy's install generator.
$ bundle exec rails g bootsy:install
Among other things, this adds an initializer to your project. Edit the initializer to override Booty's default editor options. Uncomment the lines related to default editor options, and change them as follows:
/config/initializers/bootsy.rb
Bootsy.setup do |config|
# Default editor options
# You can override them locally by passing an editor_options hash to bootsy_area
config.editor_options = {
font_styles: false,
emphasis: true,
lists: true,
html: true,
link: true,
image: false,
color: false
}
To use a Bootsy editor in place of a textarea, we simply replace the text_area
helper with the bootsy_area
helper.
<%= form_for @note do |f| %>
<p>
<%= f.text_field :title %>
</p>
<p>
<%= f.bootsy_area :body_html %>
</p>
<div class="form-actions">
<%= f.submit class: 'btn btn-default' %>
</div>
<% end %>
Don't forget to restart your server before checking it out in a browser. If you already restarted following bundle install
, you'll need to do it again once you've edited the initializer.
Let's add placeholder text to both the title
and body_html
fields.
<%= form_for @note do |f| %>
<p>
<%= f.text_field :title, placeholder: 'Title your note' %>
</p>
<p>
<%= f.bootsy_area :body_html, placeholder: 'Just start typing...' %>
</p>
<div class="form-actions">
<%= f.submit class: 'btn btn-default' %>
</div>
<% end %>
We also want the title
field to be focused when creating a new page. When editing an existing page, focusing the title
makes less sense. Let's create a helper method to determine when we should and shouldn't focus the title
field.
app/helpers/application_helper.rb
def title_autofocus?(note)
note.new_record?
end
We'll call the helper from our partial, passing in the form object (i.e. the note instance).
<%= f.text_field :title, placeholder: 'Title your note', autofocus: title_autofocus?(f.object) %>
Does everything look good? Commit!