ruby - Best way to list where everywhere a module has been included -
of course, achieve ask in title, possible write following code:
module foo class << self def included receiver my_herd << receiver end def my_herd; @my_herd ||= [] end alias where_everywhere_am_i_included my_herd end end foo.where_everywhere_am_i_included #=> [] module bar include foo end foo.where_everywhere_am_i_included #=> [bar] # etc.
i can imagine worse ways this, such search objectspace
modules , grep ancestries. want know, there better way? forgetting something, such method module#included_in
. missing clever eg. famous #append_features
method? whath better alternatives have?
edited: real world problem solving related my library sy, provides physical unit methods. physical unit methods, such 1.metre
, 1.m
, 1.s
, 1.lb
, 1.k
, tend simple symbols prone collisions. eg. activesupport
defines time methods #hour
, #minute
, #second
on numeric
. sy defines methods #hour
alias #h
, #minute
alias #min
, #second
alias #s
on numeric
means of mixin providing #method_missing
reacting unit methods. people use activesupport
have #hour
, #minute
, #second
defined , therefore #method_missing
won't kick in. still can access sy
methods #h
, #min
, #s
abbreviations, that's besides point. point is, people should warned when mixin finds possible collisions in modules in included. achieved coding collision check in module#included
hook. problem user may define unit dynamically, such as:
pint = unit.of volume, amount: 568.26.cm³ quart = unit.of volume, amount: 2.pint
but 1 can imagine user has method #quart
defined on numeric
, doing else, such computing 1 quarter of receiver, or returning 4th musical interval relative receiver etc. when ze calls quart = unit#of...
constructor, want ask mixin sy::expressibleinunits
report everywhere has been mixed in, , warn after seeing collision in numeric
. want save user surprises , i'm wondering virtuous (using avdi's trademark word) way it.
using method_added
allow provide warning in real world scenario.
module methodadded def self.included(base) base.extend(classmethods) end module classmethods def method_added(method_name) if method_name == :my_magic puts 'so sorry did not code, not bother now' end end end end class include methodadded def my_magic 'i can create method without worries.' end end
here's example of unlikely risk of extending classmethods mention in comments.
module classmethods def self.extended(base) puts 'i going sorts of evil stuff now' end end module methodadded def self.included(base) base.extend(classmethods) end module claszmethods #intentional typo demonstrate "risk" end end
Comments
Post a Comment