What is a Rails plugin?
A Rails plugin is either an extension or a modification of the core framework. It provides a way for rails developer to share bleeding-edge ideas without hurting the stable code base. We need to decide if our plugin will be potentially shared across different Rails applications.
A plugin creates models, view helpers, controllers, rake tasks, images, style sheets, javascripts, test assertions and unit and functional tests like rails application.
How to create a plugin?
desktop:~$ ruby /script/generate plugin HelloWorld (In rails < 3 version)
desktop:~$ rails generate plugin HelloWorld (In rails >= 3 version)
create vendor/plugins/hello_world/lib
create vendor/plugins/hello_world/tasks
create vendor/plugins/hello_world/test
create vendor/plugins/hello_world/README
create vendor/plugins/hello_world/Rakefile
create vendor/plugins/hello_world/init.rb
create vendor/plugins/hello_world/install.rb
create vendor/plugins/hello_world/lib/hello_world.rb
create vendor/plugins/hello_world/tasks/hello_world_tasks.rake
create vendor/plugins/hello_world/test/hello_world_test.rb
Plugin structure as,
HelloWorld
|-- init.rb
|-- install.rb
|-- Rakefile
|-- README
|-- lib/
| |-- hello_world.rb
|-- tasks/
| |-- hello_world_tasks.rake
|-- test
| |-- hello_world_test.rb
Plugin HelloWorld structure:
Here,
-> init.rb: Runs every time the rails app gets started. It is useful for mixing-in a helper module so that all of our ‘views’ can use it.
-> install.rb: Runs one time only when the plugin is first installed.
-> Rakefile: Generates documentation and runs tests for the created plugin.
-> lib/: Contains actual ruby code. New models and other libraries in this folder will be automatically available to rails app. Helpers can be included specially, using the init.rb file.
-> tasks/: Drop a .rake file here as you would in lib/tasks.
-> test/: Write tests to verify the task of our plugin.
We need hello_world/init.rb and main class in hello_world/lib/hello_world.rb to create a simple rails plugin.
We just add the required 'hello_world' in init.rb file, then create the main class hello_world.rb under hello_world/lib/ folder like the structure,
class HelloWorld
def display
"Hello World!"
end
end
That's it. We can add this plugin method in our rails controller to show the 'Hello World'.
class SamplesController < ApplicationController
def index
@show = HelloWorld.new # @show is an object to the HelloWorld class
end
end
In app/views/samples/index.html.erb
<p><%= @show.display %></p>
It shows Hello World!
Note: Restart the server if you are going to do some modifications in the plugin.
Ruby on rails consulting for Mac, Windows or Linux can make application development faster and simpler using rails plugins.