Add convenience methods for getting a struct from a ruby object.

If we are trying to get the struct from something other than self, then we
should make sure to check the class of the object.  This util functions
make this easier.
This commit is contained in:
Dylan Thacker-Smith
2014-02-28 10:08:21 -05:00
parent dc8a34a52f
commit 03d586aafe
7 changed files with 40 additions and 10 deletions

View File

@@ -1,6 +1,5 @@
#include "liquid_ext.h"
extern VALUE mLiquid, cLiquidTokenizer, cLiquidTag, cLiquidTemplate, cLiquidVariable;
VALUE cLiquidBlock;
ID intern_assert_missing_delimitation, intern_block_delimiter, intern_is_blank, intern_new,
intern_new_with_options, intern_tags, intern_unknown_tag, intern_unterminated_tag,
@@ -46,14 +45,7 @@ static bool parse_tag(struct liquid_tag *tag, char *token, long token_length)
static VALUE rb_parse_body(VALUE self, VALUE tokenizerObj)
{
Check_Type(tokenizerObj, T_DATA);
if (RBASIC_CLASS(tokenizerObj) != cLiquidTokenizer) {
rb_raise(rb_eTypeError, "wrong argument type %s (expected %s)",
rb_obj_classname(tokenizerObj),
rb_class2name(cLiquidTokenizer));
}
struct liquid_tokenizer *tokenizer;
Data_Get_Struct(tokenizerObj, struct liquid_tokenizer, tokenizer);
struct liquid_tokenizer *tokenizer = LIQUID_TOKENIZER_GET_STRUCT(tokenizerObj);
bool blank = true;
VALUE nodelist = rb_iv_get(self, "@nodelist");

View File

@@ -3,4 +3,6 @@
void init_liquid_block();
extern VALUE cLiquidBlock;
#endif

View File

@@ -7,5 +7,9 @@
#include "tokenizer.h"
#include "block.h"
#include "utils.h"
extern VALUE mLiquid;
extern VALUE cLiquidTemplate, cLiquidTag, cLiquidVariable;
#endif

View File

@@ -1,7 +1,6 @@
#include "liquid_ext.h"
VALUE cLiquidTokenizer;
extern VALUE mLiquid;
static void free_tokenizer(void *ptr)
{

View File

@@ -1,6 +1,8 @@
#ifndef LIQUID_TOKENIZER_H
#define LIQUID_TOKENIZER_H
extern VALUE cLiquidTokenizer;
enum token_type {
TOKEN_NONE,
TOKEN_INVALID,
@@ -23,4 +25,6 @@ struct liquid_tokenizer {
void init_liquid_tokenizer();
void liquid_tokenizer_next(struct liquid_tokenizer *tokenizer, struct token *token);
#define LIQUID_TOKENIZER_GET_STRUCT(obj) ((struct liquid_tokenizer *)obj_get_data_ptr(obj, cLiquidTokenizer))
#endif

21
ext/liquid/utils.c Normal file
View File

@@ -0,0 +1,21 @@
#include <ruby.h>
void raise_type_error(VALUE expected, VALUE got)
{
rb_raise(rb_eTypeError, "wrong argument type %s (expected %s)",
rb_class2name(got), rb_class2name(expected));
}
void check_class(VALUE obj, int type, VALUE klass)
{
Check_Type(obj, type);
VALUE obj_klass = RBASIC_CLASS(obj);
if (obj_klass != klass)
raise_type_error(klass, obj_klass);
}
void *obj_get_data_ptr(VALUE obj, VALUE klass)
{
check_class(obj, T_DATA, klass);
return DATA_PTR(obj);
}

8
ext/liquid/utils.h Normal file
View File

@@ -0,0 +1,8 @@
#ifndef LIQUID_UTILS_H
#define LIQUID_UTILS_H
void raise_type_error(VALUE expected, VALUE got);
void check_class(VALUE klass);
void *obj_get_data_ptr(VALUE obj, VALUE klass);
#endif