haml--haml/ext/hamlit/hamlit.c

75 lines
1.7 KiB
C
Raw Normal View History

2015-11-25 16:07:06 +00:00
#include <ruby.h>
#include <ruby/encoding.h>
#include "houdini.h"
2015-11-25 16:07:06 +00:00
2015-11-26 16:57:18 +00:00
VALUE mAttributeBuilder;
2015-11-26 16:18:02 +00:00
static ID id_flatten, id_join;
2015-11-26 16:57:18 +00:00
static ID id_underscore;
2015-11-26 16:18:02 +00:00
static VALUE
escape_html(VALUE str)
{
gh_buf buf = GH_BUF_INIT;
Check_Type(str, T_STRING);
if (houdini_escape_html0(&buf, (const uint8_t *)RSTRING_PTR(str), RSTRING_LEN(str), 0)) {
str = rb_enc_str_new(buf.ptr, buf.size, rb_utf8_encoding());
gh_buf_free(&buf);
}
return str;
}
2015-11-25 17:12:05 +00:00
static VALUE
attr_build_id(VALUE escape_attrs, VALUE ids)
{
VALUE truthy_ids, id, attr_value;
2015-11-26 16:25:31 +00:00
int i, len;
2015-11-25 17:12:05 +00:00
2015-11-26 16:18:02 +00:00
ids = rb_funcall(ids, id_flatten, 0);
2015-11-25 17:12:05 +00:00
2015-11-26 16:25:31 +00:00
len = RARRAY_LEN(ids);
2015-11-26 17:09:25 +00:00
truthy_ids = rb_ary_new2(len);
2015-11-26 16:25:31 +00:00
for (i = 0; i < len; i++) {
2015-11-25 17:12:05 +00:00
id = rb_ary_entry(ids, i);
if (!NIL_P(id) && id != Qfalse) {
rb_ary_push(truthy_ids, id);
}
}
2015-11-26 16:57:18 +00:00
attr_value = rb_funcall(truthy_ids, id_join, 1, rb_const_get(mAttributeBuilder, id_underscore));
2015-11-25 17:12:05 +00:00
if (RTEST(escape_attrs)) {
attr_value = escape_html(attr_value);
2015-11-25 17:12:05 +00:00
}
return attr_value;
}
static VALUE
rb_attr_build_id(int argc, VALUE *argv, RB_UNUSED_VAR(VALUE self))
{
VALUE array;
rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
rb_scan_args(argc - 1, argv + 1, "*", &array);
return attr_build_id(argv[0], array);
}
2015-11-25 16:07:06 +00:00
void
Init_hamlit(void)
{
2015-11-26 16:57:18 +00:00
VALUE mHamlit;
2015-11-25 17:12:05 +00:00
mHamlit = rb_define_module("Hamlit");
mAttributeBuilder = rb_define_module_under(mHamlit, "AttributeBuilder");
rb_define_singleton_method(mAttributeBuilder, "build_id", rb_attr_build_id, -1);
2015-11-26 16:18:02 +00:00
id_flatten = rb_intern("flatten");
id_join = rb_intern("join");
2015-11-26 16:57:18 +00:00
id_underscore = rb_intern("UNDERSCORE");
2015-11-26 17:02:18 +00:00
rb_const_set(mAttributeBuilder, id_underscore, rb_obj_freeze(rb_str_new_cstr("_")));
2015-11-25 16:07:06 +00:00
}