Ruby caller_location

I am trying to convert ruby/lib/un.rb at master · ruby/ruby · GitHub to a similar type of file in ruby. It uses caller_locations to find who called it. Is a similar function available in Crystal?

Here’s the relevant code

def setup(options = '', *long_options)
  caller = caller_locations(1, 1)[0].label
  opt_hash = {}
  argv = []
  OptionParser.new do |o|
    options.scan(/.:?/) do |s|
      opt_name = s.delete(':').intern
      o.on('-' + s.tr(':', ' ')) do |val|
        opt_hash[opt_name] = val
      end
    end
    long_options.each do |s|
      opt_name, arg_name = s.split(/(?=[\s=])/, 2)
      opt_name.delete_prefix!('--')
      s = "--#{opt_name.gsub(/([A-Z]+|[a-z])([A-Z])/, '\1-\2').downcase}#{arg_name}"
      puts "#{opt_name}=>#{s}" if $DEBUG
      opt_name = opt_name.intern
      o.on(s) do |val|
        opt_hash[opt_name] = val
      end
    end
    o.on('-v') { opt_hash[:verbose] = true }
    o.on('--help') do
      UN.help([caller])
      exit
    end
    o.order!(ARGV) do |x|
      if /[*?\[{]/ =~ x
        argv.concat(Dir[x])
      else
        argv << x
      end
    end
  end
  yield argv, opt_hash
end

1 Like

Probably are looking for Top Level Namespace - Crystal 1.14.0, but isn’t going to be as nice to work with.

Related: Improve Exception backtrace API · Issue #10681 · crystal-lang/crystal · GitHub