Expandable
Expandable is a Rails gem that allows you to take that big ugly model codes and break it up into many small chunks of organized codes in different files.
It also helps you to break large business logic in controllers in to little pirces. Usually you want to have the business logic out of the controller and in to the model however there are rare times when you just simply can not.
Installation
Add this line to your application's Gemfile:
gem 'expandable'
And then execute:
$ bundle
Setup
The first step is to make sure that this folder exist app/models/expandables
.
You can either create the file yourself of run the generator:
rails generate expandable:init
Usage
This gem is very easy to use in just three steps.
First
Create a folder in app/models/expandables
where the name of the
folder is the model name. For an example the book model
will be app/models/expandables/book
.
Second
Create a file with any name and make sure that then end of the file
name ends with the underscore model name and the extension. For an example
the book model will have an expandable in
app/models/expandables/book/foo_book.rb
.
Third
Make sure that the file is a module type. For example the foo_book.rb will the the structure:
module FooBook
def foo
'bar'
end
end
Now all you have to do is just use it. Here is an example:
Book.new.foo
'bar'
The same principle applys to controllers as well.
Class Methods
If you like to make an expandable in to a class method then all you have to do
is chnge the file name and module name by adding a self_ infront of it. For
an example for book model it will be
app/models/expandables/book/self_foo_book.rb
.
The codes will look like this:
module SelfFooBook
def
'foo'
end
end
Now all you have to do is:
Book.
'foo'
Simple right? Now start organizing your codes and make your application shine.
Limitations
The gem has few limitations such as:
Only one model can use its counter parts.
You can not have another model load book's modules. This is done purposely to stop the clutter. If you have a module that needs to be loaded in two or more models then use "concerns" and include the modules in each models that needs it.
Restart Or Reload Needed On Change
Dispite my best effort I was unable to have the module auto reload on change. This means every time you make a change to the modules it will not load unless you close and start the application again.