I have a simple ruby function:
module MyModule
def foo(param)
puts param
end
end
I want to be able to make calls with undefined tokens like bar
and Baz
, as follows:
foo bar
foo Baz
Note that I need to be able to pass any token name that begins with an a letter (lower or upper case).
I can handle the first case (lower case beginning name, bar
) by adding a method_missing:
module MyModule
def method_missing(meth, *args, &blk)
meth.to_s
end
end
But the second line (with Baz
) gives me an uninitialized constant error, so I tried adding a similar const_missing:
module MyModule
def const_missing(const_name)
const_name.to_s
end
end
But I still get the uninitialized constant error with Baz
- how do I trap missing names beginning with upper case and return the string?
Update: Here is the full code to repro the scenario:
module MyModule
def foo(param)
puts param
end
def method_missing(meth, *args, &blk)
meth.to_s
end
def const_missing(const_name)
const_name.to_s
end
end
include MyModule
foo "bar" #=> bar
foo bar #=> bar
foo Baz #=> uninitialized constant Baz (NameError)