You can use method definition within methods, so those inner methods are defined when parent method is called:
class A
def self.define_foo
def foo
:foo
end
end
end
a = A.new
a.foo #=> undefined method foo
A.define_foo
a.foo #=> :foo
This however is rather rare, as methods defined that way has no access to params passed to the parent. Much more useful is to use define_method
which carries binding the method has been created in:
class A
def self.define_sth(sth)
define_method sth do
sth
end
end
end
a = A.new
a.bar #=> undefined method bar
A.define_sth(:bar)
a.bar #=> :bar
This is being used for example by rails when defining associations. When you call Parent.has_one :child
, method has_one
calls define_method
to create child
, child=
, build_child
and create_child
methods.
As for stubbing, methods created that way are no different from any other methods, you just stub them as usual.