#to_svelte

#to_svelte helps to streamline attributes from ActiveRecord to svelte:

There are limitations on Ruby-2x because keyword arguments are not supported. However, it should work for basic usage (we have it on our customer’s app).

ActiveRecord instance

@book.to_svelte(:title)
# => {
#        book_labels: { title: "Title" }
#        book: { title: "Rails Cookbook" }
#    }

ActiveRecord Relation

@books.to_svelte(:title)
# => {
#        book_labels: { title: "Title" }
#        book: [{ title: "Rails Cookbook" }]
#    }
  • Returns values in a array
  • Labels are always extracted, even if the relation does not contain a record

ActiveRecord Model

Book.to_svelte(:title)
# => {
#        book_labels: { title: "Title" }
#    }
  • Only labels are extracted.

More detailled example

@book.to_svelte(
  :name,
  :calculation_method,
  author: [:name],
  editions: [
    :date,
    offset: 2,
    limit: 1
  ]
)

Output

{
  "book" => {
    "name" => "Learning Ruby",
    "calculation_method" => "any-result",
    "author" => {
      "name" => "Michael Hartl"
    },
    "editions" => [
      { "date" => "2025-02-03" }
    ]
  },
  "book_labels" => {
    "name" => "Name",
    "calculation_method" => "Calculation Method",
    "author" => "Author"
  },
  "author_labels" => {
    "name" => "Name"
  },
  "edition_labels" => {
    "date" => "Date"
  }
}

Enums

Assuming genre is a enum, @book.to_svelte(:genre) would return something like:

{
  "book" => {
    genre: "fantasy"
  },
  "book_labels" => {
    "genre" => "Genre"
  },
  "book_enums" => [
    [ 
      "fantasy", 
      "Fantasy" # => Translated label
    ] 
  ]
}

STATUS: This is not working on enums of associated models (tdb.)

Reserved Keys

The keys offset and limit are reserved for pagination control within associations. If your model has columns named offset or limit, they will be ignored to avoid conflicts.

Pagination Options

When querying associations, you can use the following options:

  • offset: Skips the specified number of records (e.g., offset: 2).
  • limit: Restricts the number of records returned (e.g., limit: 1).

Caching

The #to_svelte method does not include built-in caching. However, you can wrap it with a caching layer (e.g., Redis) for performance optimization. When used with the cached_svelte_component view helper, the component’s attributes generate a checksum that serves as a cache key for efficient storage and retrieval.


Copyright © 2025-2027 sedlmair.ch. Distributed by MIT license.