Module: CParser

Defined in:
ext/parser/parser.c

Class Method Summary collapse

Class Method Details

.parse_address(*args) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'ext/parser/parser.c', line 51

VALUE rb_parse_address(int argc, VALUE *argv, VALUE self) {
    if (argc < 2) {  // there should only be 1 or 2 arguments
        rb_raise(rb_eArgError, "Usage: parse_address(address, options = {})");
        return Qnil;
    }

    VALUE input;
    VALUE rb_options;

    rb_scan_args(argc, argv, "2", &input, &rb_options);

    if (TYPE(input) != T_STRING) {
        rb_raise(rb_eArgError, "input must be a string");
        return Qnil;
    }

    if (TYPE(rb_options) != T_HASH) {
        rb_raise(rb_eArgError, "options must be a hash");
        return Qnil;
    }

    VALUE rb_language = hash_get_symbol_or_string(rb_options, "language");
    VALUE rb_country = hash_get_symbol_or_string(rb_options, "country");

    char *address = RSTRING_PTR(input);

    libpostal_address_parser_response_t *parsed;
    libpostal_address_parser_options_t options = libpostal_get_address_parser_default_options();
    if (rb_language != Qnil) {
        options.language = RSTRING_PTR(rb_language);
    }

    if (rb_country != Qnil) {
        options.country = RSTRING_PTR(rb_country);
    }

    if ((parsed = libpostal_parse_address(address, options))) {
        size_t n = parsed->num_components;
        VALUE rb_parse_result = rb_ary_new2(n);

        for (size_t i = 0; i < n; i++) {
            VALUE rb_component = rb_ary_new2(2);
            rb_ary_store(rb_component, 0, rb_str_new2(parsed->components[i]));
            rb_ary_store(rb_component, 1, ID2SYM(rb_intern(parsed->labels[i])));

            rb_ary_store(rb_parse_result, i, rb_component);
        }

        libpostal_address_parser_response_destroy(parsed);

        return rb_parse_result;
    }

    return Qnil;

}