HowTo Write An ActsAsChicken Plugin

From: http://wiki.rubyonrails.org/rails/pages/HowTosPlugins

See also Plugins

SomeImportantPluginNotes – before you start

Thanks to Kev Jackson and Jamis Buck for their help getting me started with writing acts_as_* plugins. This is a summary and plagiarism of their emails

This plugin adds a class method to a model that acts_as_chicken

A 6 step program to acting like a chicken…

Step 1

under your_app/vendor/plugins

create a directory “acts_as_chicken”

Step 2

in this directory create a lib directory

so now you should have

your_app/vendor/plugins/acts_as_chicken/lib

Step 3

in the acts_as_chicken directory create the following file with this content:

your_app/vendor/plugins/acts_as_chicken/init.rb

require 'acts_as_chicken'

Step 4

in the lib subdirectory add your code to a file called acts_as_chicken.rb

your_app/vendor/plugins/acts_as_chicken/lib/acts_as_chicken.rb

require 'active_record'

module Foo
  module Acts #:nodoc:
    module Chicken #:nodoc:

      def self.append_features(base)
        super
        base.extend(ClassMethods)
      end

      module ClassMethods
        def acts_as_chicken
          class_eval do
            extend Foo::Acts::Chicken::SingletonMethods
          end
        end
      end

      # add your class methods here
      module SingletonMethods
        def cluck
          'cluck'
        end
        #etc...
      end

    end
  end
end

ActiveRecord::Base.class_eval do
  include Foo::Acts::Chicken
end

Step 5

Use your method in your classes

class Hen < ActiveRecord::Base
 acts_as_chicken
end

Step 6

Use your method in your view.

<%= Hen.cluck %>

 

Jamis Buck suggested using some name like Foo in the above because “this will allow (potentially) multiple developers to develop identically-named features without conflict.” Other people use “ActiveRecord” in place of the three “Foo”. Jamis doesn’t like this use of ActiveRecord. He says “I’ve noticed many plugin developers taking this particular route, and I’d like to discourage it, strenuously. There really is no need to add your own acts to the ActiveRecord::Acts namespace. Instead, I’d encourage the creation of your own Acts namespace like Foo”

HowTosPlugins – Some tutorials to get started


What is missing here is a good description of the Ruby magic that is happening in step 4. Can someone in the know add this (then remove this message).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值