Rails Plugins

Seth Thomas Rasmussen

Opposite of Sequitur

Overview

  1. What are plugins in Rails?
  2. Why use them?
  3. Examples
  4. Beyond here..

Yay, you know how to print!

What are plugins in Rails?

A Rails plugin is either an extension or a modification of the core framework. Plugins provide:

Why use them?

Organized, standardized, encapsulated
discover, download and manage your plugins with script/plugin
generate stub code in a standard format with script/generate plugin
update plugins from separate source repositories using svn:externals
Advice from others
Five reasons why your next Rails mod should be a plugin
Rails Views: Internal Plugins
folder_for :student do                                                                                                               
  tabs :general, :attendance, :surveys
  tab :report do
    # get report data
  end
end

Examples:

Map Select Options
Simple extension of Array using only init.rb
Map Select Options: REDUX
Simple extension of ActiveRecord::Base using only init.rb
Findar
Extending Rails and getting a little more dynamic
Acts as Authenticated
Perhaps not so much a plugin as it is a generator factory

Examples: Map Select Options

# init.rb
class Array
  def map_select_options(display = :name, value = :id)
    map { |x| [ x.send(display) , x.send(value) ] }
  end
end

# controller
@options = Model.find(
  :all, :select => 'name,id', :order => 'name'
).map_select_options

# view
select :object, :attribute, @options

Examples: Map Select Options: REDUX

# init.rb
class << ActiveRecord::Base
  def map_select_options(display = :name, value = :id, o = {})
    o = {:select => "#{display},#{value}",
         :order => display}.update(o)
    find(:all, o).map { |x| [ x.send(display) , x.send(value) ] }    
  end
end

# controller
@options = Model.map_select_options
# view
select :object, :attribute, @options

Examples: Findar

module Findar
  def self.included(receiver)
    super
    constants.each do |c|
      receiver.extend eval(c) if eval(c).is_a? Module
    end
  end
  
  module MiscFinders
    def find_random(o = {})
      o[:order] = 'rand()'
      find :first, o
    end
    alias_method :random, :find_random
  end
end

Examples: Acts as Authenticated

Author: Rick Olson

acts_as_authenticated is not really a typical plugin that modifies Rails. It's more of a generator for the authentication methods. I went with a generator because it's designed as a basic starting point that will probably (and should be) modified to fit your app's exact needs. .

Beyond here..

Rails Plugins

Seth Thomas Rasmussen

Opposite of Sequitur