3 unstable releases

0.8.1 Jan 26, 2024
0.8.0 Oct 19, 2023
0.7.0 Jul 6, 2023
0.2.2 Mar 22, 2023
0.1.1 Jan 22, 2023

#52 in FFI

Download history 102/week @ 2023-12-23 119/week @ 2023-12-30 143/week @ 2024-01-06 245/week @ 2024-01-13 96/week @ 2024-01-20 101/week @ 2024-01-27 492/week @ 2024-02-03 170/week @ 2024-02-10 228/week @ 2024-02-17 503/week @ 2024-02-24 293/week @ 2024-03-02 219/week @ 2024-03-09 161/week @ 2024-03-16 164/week @ 2024-03-23 305/week @ 2024-03-30 978/week @ 2024-04-06

1,640 downloads per month
Used in pks

MIT license

55KB
807 lines

serde_magnus

serde_magnus converts between Rust and Ruby data structures using Serde and Magnus.

Quick links

Usage

The serde_magnus::serialize function converts from a Rust type implementing the serde::Serialize trait into a Ruby equivalent.

use serde::{Serialize, Deserialize};
use magnus::{eval, Value};
use serde_magnus::serialize;

#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Post {
    title: String,
    content: String,
    author: Author,
    tags: Vec<String>
}

#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Author {
    name: String,
    email_address: String
}

let post = Post {
    title: "Spring carnival planning update".into(),
    content: "Here's what's new.".into(),
    author: Author {
        name: "Martha".into(),
        email_address: "martha@example.com".into()
    },
    tags: vec![
        "carnival".into(),
        "update".into()
    ]
};

let post: Value = serialize(&post)?;

assert!(eval!(
    r#"
    post == {
      title: "Spring carnival planning update",
      content: "Here's what's new.",
      author: {
        name: "Martha",
        email_address: "martha@example.com"
      },
      tags: ["carnival", "update"]
    }
    "#,
    post
)?);

serde_magnus::deserialize converts from a Ruby value to a Rust type implementing serde::Deserialize.

use magnus::RHash;
use serde_magnus::deserialize;

let post: RHash = eval!(r#"
  {
    title: "Spring carnival planning update",
    content: "Here's what's new.",
    author: {
      name: "Martha",
      email_address: "martha@example.com"
    },
    tags: ["carnival", "update"]
  }
"#)?;

let post: Post = deserialize(post)?;

assert_eq!(
    Post {
        title: "Spring carnival planning update".into(),
        content: "Here's what's new.".into(),
        author: Author {
            name: "Martha".into(),
            email_address: "martha@example.com".into(),
        },
        tags: vec![
            "carnival".into(),
            "update".into()
        ]
    },
    post
);

Requirements

serde_magnus requires Rust 1.65+ and Ruby 3.0+.

License

serde_magnus is released under the terms of the MIT License. See LICENSE for details.

Dependencies

~1.5–4.5MB
~73K SLoC