Some question about classes in plugin
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? Railsstatement is outside themodulestatement? When will be run istructions inside that?What means and how can\should I use
class << self?
module WillPaginatedefines Ruby name scope and groups these methods so they can be later included with one call into some class. Theif defined? Railsis outside the module because the code inside thatifmight include the whole module into some ActiveRecord class. And theifis executed exactly at the time whenwill_paginate.rbfile 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.
加载中,请稍侯......
精彩评论