Skip to content

API: Pretty::Method

maiha edited this page Feb 12, 2018 · 2 revisions

Pretty::Method helps meta programming on Crystal. Its call method invokes methods dynamically via string of method name.

Pretty.method(instance)

This is a shortcut for Pretty::Method(T).new(instance).

Pretty.method(1.5).call("ceil") # => 2.0

Pretty::Method(T)#call(name : String)

This invokes method represented by given string and returns the result T if the method exists. Otherwise, it raises Pretty::Method::NotFound.

method = Pretty::Method(String).new("UserName")
method.call("underscore") # => "user_name"
method.call("upcase")     # raises Pretty::Method::NotFound

Although String#upcase exists, it raises NotFound. Because Pretty::Method currently supports only following methods.

  1. public methods
  2. no arguments (include optional)
  3. no blocks
  4. defined in the class not in ancestors

Pretty::Method(T)#call?(name : String)

This is same as call except it returns nil rather than raising errors when method doesn't exist.

method = Pretty::Method(Array(Int32)).new([1,2])
method.call?("size")   # => 2
method.call?("upcase") # => nil