SlotMachine
Slot Machine is a rails plugin to help you write clean, readable views. It hides the ugly css in partials away from your views. Slot Machine transforms partials into helper methods. Each partial contains slots into which you can insert data, html or other partials.
Installation
Add this line to your application's Gemfile:
gem 'slot_machine'
And then execute:
$ bundle
Or install it yourself as:
$ gem install slot_machine
In your application controller
helper SlotMachine.helper_module(path: Rails.root.join('app/views/slots/_*'))
Path can also be an Array
include SlotMachine::ControllerConcern
helper slot_machine_helper(path: ['my_path/_*','my_other_path/_*' ])
Usage
The simplest case
Create your first partial (app/views/slots/_my_first_partial.html.slim)
.my_first_partial #This is not required just an example
h2 = slots[:title]
h3 = slots[:subtitle]
.content
= slots[:content]
You can now write in your view:
= my_first_partial title: 'foo', subtitle: 'bar', content: 'awesome content'
or more usefull
= my_first_partial title: 'foo', subtitle: 'bar' do |mfp|
- mfp.slot :content
div this is great
A more interesting example
So far you could do the same with a partial. I know let's try something better.
The slot main
First there is a special slot by default: slots[main]
_card.html.slim
.card
.card__title = slots[:title]
.card__content
= slots[:main] # yep that's the one
you can now do:
= card title: 'foo' do
div this is great
More then one slot
_modal.html.slim
.modal
.modal__title = slots[:title]
.modal__content
= slots[:main]
.modal__footer
= slots[:footer]
It allows you to write something like this:
= modal title: 'foo' do |modal|
div hey look I'm a modal
- modal.slot :footer
div With a footer
And combine
With the two partials from before (modal and card) we can now do this:
= modal title: 'foo' do |modal|
= card title: 'a card in a modal' do
div And wait there is still more
- modal.slot :footer
= card title: 'a card in a modal\'s foot' do
div My example are getting a bit far fetched
What else?
You noticed all my examples are with slim. But it work great with yaml or erb.
I also name my partials with the BEM notation. I find it easier to organise them by components specialy if you already use this same notation with your css.
License
The gem is available as open source under the terms of the MIT License.