Module: FastUnderscore

Defined in:
lib/fast_underscore/version.rb,
ext/fast_underscore/fast_underscore.c

Constant Summary collapse

VERSION =
'0.0.1'

Class Method Summary collapse

Class Method Details

.underscore(rb_string) ⇒ Object

Makes an underscored, lowercase form from the expression in the string.

Changes ‘::’ to ‘/’ to convert namespaces to paths.

underscore('ActiveModel')         # => "active_model"
underscore('ActiveModel::Errors') # => "active_model/errors"

As a rule of thumb you can think of underscore as the inverse of #camelize, though there are cases where that does not hold:

camelize(underscore('SSLError'))  # => "SslError"


346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'ext/fast_underscore/fast_underscore.c', line 346

static VALUE
rb_str_underscore(VALUE self, VALUE rb_string) {
  rb_encoding *encoding = rb_enc_from_index(ENCODING_GET(rb_string));

  char *string = RSTRING_PTR(rb_string);
  char *end = RSTRING_END(rb_string);

  builder_t *builder = builder_build(RSTRING_LEN(rb_string) * 2);
  codepoint_t *codepoint = codepoint_build(encoding);

  while (string < end) {
    codepoint->character = rb_enc_codepoint_len(string, end, &codepoint->size, encoding);
    builder_next(builder, codepoint);
    string += codepoint->size;
  }
  builder_flush(builder);

  VALUE resultant = rb_enc_str_new(builder->result, builder->result_size, encoding);
  builder_free(builder);

  return resultant;
}