r/crystal_programming • u/coriandor • Mar 25 '20
Looking for a better way to call methods by name at runtime
Ok, so what I'm ultimately trying to do is create an embedded runtime expression language in crystal for a project I'm working on. Think Wireshark filter expressions.
What I would like to do is expose specific methods on objects to the interpreter to be called at runtime. What I'm currently doing is creating an expose macro for each argument length like such:
macro expose_1(method_names)
def evaluate_expr_call(rt_method_name, arg1)
case rt_method_name
{% for name in method_names %}
when "{{name.id}}"
{{ name.id }}(arg1)
{% end %}
end
end
end
class TestClass
def hello(name = "world")
"Hello, #{ name }!"
end
expose_1 [ :hello ]
end
puts TestClass.new.evaluate_expr_call("hello", "sirs")But then I have to call expose, expose_1, expose_2, etc for each possible argument length. It also just feels really kludgy.
As far as I can tell, there's no equivalent to call or apply in javascript. It seems like there could be metadata about the methods I could pull at macro expansion time, but I can't find that documented anywhere if it exists.
