Tobias L??tke??™s Active Merchant Rails plugin uses
this approach for the view helpers. First, a module is created with the helper method:
Metaprogramming Techniques | 35
module ActiveMerchant
module Billing
module Integrations
module ActionViewHelper
def payment_service_for(order, account, options = {}, &proc)
...
end
end
end
end
end
Then, in the plugin??™s init.rb script, the module is included in ActionView::Base:
require 'active_merchant/billing/integrations/action_view_helper'
ActionView::Base.send(:include,
ActiveMerchant::Billing::Integrations::ActionViewHelper)
It certainly would be simpler in code to directly open ActionView::Base and add the
method, but this has the advantage of modularity. All Active Merchant code is contained
within the ActiveMerchant module.
There is one caveat to this approach. Because any included modules are searched for
methods after the class??™s own methods are searched, you cannot directly overwrite a
class??™s methods by including a module:
module M
def test_method
"Test from M"
end
end
class C
def test_method
"Test from C"
end
end
C.send(:include, M)
C.new.test_method # => "Test from C"
Instead, you should create a new name in the module and use alias_method_chain:
module M
def test_method_with_module
"Test from M"
end
end
class C
def test_method
"Test from C"
end
end
36 | Chapter 1: Foundational Techniques
# for a plugin, these two lines would go in init.
Pages:
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68