开发者

Some question about classes in plugin

开发者 https://www.devze.com 2023-02-16 20:13 出处:网络
I am using Ruby on Rails 3 and and I am t开发者_Go百科rying to implement a new plugin. In order to learn, I am viewing inside and I am studying some popular plugins.

I am using Ruby on Rails 3 and and I am t开发者_Go百科rying to implement a new plugin. In order to learn, I am viewing inside and I am studying some popular plugins.

What I choosed is WillPaginate and in a its file there is something like this:

module WillPaginate
  class << self
    ...
  end
end

if defined? Rails
  WillPaginate.enable_activerecord if defined? ActiveRecord
  WillPaginate.enable_actionpack if defined? ActionController
end

I would like to know

  1. Why the if defined? Rails statement is outside the module statement? When will be run istructions inside that?

  2. What means and how can\should I use class << self?


  1. module WillPaginate defines Ruby name scope and groups these methods so they can be later included with one call into some class. The if defined? Rails is outside the module because the code inside that if might include the whole module into some ActiveRecord class. And the if is executed exactly at the time when will_paginate.rb file is loaded.

  2. All methods in that block are class methods. So later it is possible to make calls like YourModelClass.foo.


The if defined? Rails block is evaluated at load time, ie during require 'will_paginate'. That allows will_paginate to be used with or without Rails.

The class << self section is a way to define a group of methods on the WillPaginate module without having to define them all as def self.method_name. Either way works (except for a few edge cases I can't remember now), so it's mostly just a style choice.

0

精彩评论

暂无评论...
验证码 换一张
取 消