This articles was published on 2013-05-22

[gem] mruby-config

MATSUMOTO Ryosuke just published some hours ago his new GEM mruby-config. He wrote also an article about what it is.

What is it?

With mruby we continuously switching between Ruby and C code. mruby-config gives you an easy way to maintain configuration values on both sides.

How does it work?

An example Ruby configuration could look likes this:

add_config(
    "Listen"            => 80,
    "DocumentRoot"      => "/var/www/html",
    "ExtendedStatus"    => nil,
    "User"              => "apache",
    "Group"             => "apache",
)

if get_config("Version").to_i < 2
  add_config "ExtendedStatus" => "Off"
else
  add_config "ExtendedStatus" => "On"
end

If we assume that this file was saved under the name mruby.conf the corresponding C code to read the configuration values in C could look like this:

#include <mruby.h>

static mrb_value get_config_value(mrb_state *mrb, char *key)
{
  return mrb_funcall(mrb, mrb_top_self(mrb), "get_config", 1, mrb_str_new_cstr(mrb, key));
}

int main() {

  FILE *fp;
  if ((fp = fopen("./mruby.conf", "r")) == NULL)
    return 1;

  mrb_state* mrb = mrb_open();
  mrb_load_file(mrb, fp);

  mrb_value listen_port     = get_config_value(mrb, "Listen");
  mrb_value document_root   = get_config_value(mrb, "DocumentRoot");
  mrb_value extend_status   = get_config_value(mrb, "ExtendedStatus");
  mrb_value user            = get_config_value(mrb, "User");
  mrb_value group           = get_config_value(mrb, "Group");

  mrb_close(mrb);

  return 0;
}

To work on Ruby side with these values you can, add a new configuration value:

add_config "ExtendedStatus" => "On"

Delete configuration values:

del_config "ExtendedStatus"

Read out a configuration values:

get_config "ExtendedStatus"

Have a look at the source and the examples. The implementation is quite straight forward.