minify-html/ruby/src/lib.rs

60 lines
2.2 KiB
Rust
Raw Normal View History

2021-08-07 05:57:35 -04:00
use minify_html::{minify as minify_html_native, Cfg};
use rutie::{class, methods, Boolean, Class, Hash, Object, RString, Symbol, VM};
use std::str::from_utf8;
macro_rules! get_cfg_hash_prop {
($cfg_hash:ident, $prop:literal) => {
$cfg_hash
.at(&Symbol::new($prop))
.try_convert_to::<Boolean>()
.map_or(false, |v| v.to_bool())
};
}
2020-01-19 03:19:33 -05:00
2020-07-11 11:29:34 -04:00
class!(MinifyHtml);
2020-01-19 03:19:33 -05:00
methods! {
2020-07-11 11:29:34 -04:00
MinifyHtml,
2020-01-19 03:19:33 -05:00
_itself,
fn minify(source: RString, cfg_hash: Hash) -> RString {
2021-08-07 05:57:35 -04:00
let code = source
2020-01-19 03:19:33 -05:00
.map_err(|e| VM::raise_ex(e) )
.unwrap()
.to_string()
.into_bytes();
2021-01-07 09:58:31 -05:00
let cfg_hash = cfg_hash
.map_err(|e| VM::raise_ex(e) )
.unwrap();
let cfg = &Cfg {
do_not_minify_doctype: get_cfg_hash_prop!(cfg_hash, "do_not_minify_doctype"),
ensure_spec_compliant_unquoted_attribute_values: get_cfg_hash_prop!(cfg_hash, "ensure_spec_compliant_unquoted_attribute_values"),
2021-08-07 06:16:02 -04:00
keep_closing_tags: get_cfg_hash_prop!(cfg_hash, "keep_closing_tags"),
keep_comments: get_cfg_hash_prop!(cfg_hash, "keep_comments"),
keep_html_and_head_opening_tags: get_cfg_hash_prop!(cfg_hash, "keep_html_and_head_opening_tags"),
keep_spaces_between_attributes: get_cfg_hash_prop!(cfg_hash, "keep_spaces_between_attributes"),
minify_css: get_cfg_hash_prop!(cfg_hash, "minify_css"),
minify_css_level_1: get_cfg_hash_prop!(cfg_hash, "minify_css_level_1"),
minify_css_level_2: get_cfg_hash_prop!(cfg_hash, "minify_css_level_2"),
minify_css_level_3: get_cfg_hash_prop!(cfg_hash, "minify_css_level_3"),
2021-08-07 06:16:02 -04:00
minify_js: get_cfg_hash_prop!(cfg_hash, "minify_js"),
remove_bangs: get_cfg_hash_prop!(cfg_hash, "remove_bangs"),
remove_processing_instructions: get_cfg_hash_prop!(cfg_hash, "remove_processing_instructions"),
};
2021-08-07 05:57:35 -04:00
let out_code = minify_html_native(&code, cfg);
let out_str = from_utf8(&out_code).unwrap();
2021-08-07 06:16:02 -04:00
RString::new_utf8(out_str)
2020-01-19 03:19:33 -05:00
}
}
#[allow(non_snake_case)]
#[no_mangle]
2020-07-11 11:29:34 -04:00
pub extern "C" fn Init_minify_html() {
Class::new("MinifyHtml", None).define(|itself| {
2020-01-19 03:19:33 -05:00
itself.def_self("minify", minify);
});
}