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
Why the
if defined? Rails
statement is outside themodule
statement? When will be run istructions inside that?What means and how can\should I use
class << self
?
module WillPaginate
defines Ruby name scope and groups these methods so they can be later included with one call into some class. Theif defined? Rails
is outside the module because the code inside thatif
might include the whole module into some ActiveRecord class. And theif
is executed exactly at the time whenwill_paginate.rb
file is loaded.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.
精彩评论