### Schedule Litejob Jobs in Ruby Source: https://github.com/oldmoe/litestack/wiki/Litejob-guide These examples show how to invoke Litejob jobs asynchronously, at a specific time, or after a certain delay. These methods allow for flexible job execution scheduling within a Ruby application. ```ruby # to invoke your jobs asynchronously AddJob.perform_async(1, 1) # to invoke at a certain time AddJod.perfrom_on(time, 1, 1) # to invoke after a certain delay Addjob.perform_in(delay, 1, 1) ``` -------------------------------- ### Litemetric Configuration YAML Example Source: https://github.com/oldmoe/litestack/wiki/litemetric-guide Provides an example of a Litemetric configuration file in YAML format. It specifies settings for the database file path, event buffer flush interval, data summarizer interval, and snapshot interval. This configuration helps control Litemetric's behavior and performance. ```yaml path: path/to/your/db/file flush_interval: 10 # how long are events buffered before flushing to db summarize_intervale: 30 # delay between data summarizer runs snapshot_intervale: 10*60 # how often to take snapshots from client libraries ``` -------------------------------- ### Create a Litequeue Instance (Ruby) Source: https://github.com/oldmoe/litestack/wiki/Litequeue-Guide Initializes a new Litequeue instance. Options like 'path', 'mmap_size', and 'sync' can be passed to customize queue behavior. No external dependencies are required beyond the Litequeue gem itself. ```ruby queue = Litequeue.new ``` -------------------------------- ### Litejob Configuration in YAML Source: https://github.com/oldmoe/litestack/wiki/Litejob-guide This YAML snippet outlines the configuration options for Litejob, including the database file path, queue definitions with priorities and spawning behavior, worker count, retry settings, dead job retention, and logging. ```yaml path: '/queue.db' # where the database file resides queues: - [default, 1] # default queue with the lowest priority - [urgent, 10, spawn] # this is not a default, a higher priority queue which will run every job in its own thread or fiber workers: 5 # how many threads/fibers to spawn for queue processing retries: 5 # how many times to retry a failed job before giving up retry_delay: 60 # seconds retry_delay_multiplier: 10 # 60 -> 600 -> 6000 and so on dead_job_retention: 864000 # 10 days to keep completely faild jobs in the _dead queue gc_sleep_interval: 7200 # 2 hours of sleep between checking for dead jobs that are ready to be buried forever logger: STDOUT # possible values are STDOUT, STDERR, NULL or a file location ``` -------------------------------- ### Litejob Configuration File Source: https://github.com/oldmoe/litestack/blob/master/README.md Shows an example of a `litejob.yml` configuration file used to define job queues with names, priorities, and optional concurrency settings. Priorities range from 1 to 10, and 'spawn' indicates each job runs in its own concurrency context. ```yaml queues: - [default, 1] - [urgent, 5] - [critical, 10, "spawn"] ``` -------------------------------- ### Configure Litecable with ActionCable Source: https://github.com/oldmoe/litestack/blob/master/README.md Provides an example `cable.yaml` configuration for using Litecable as an ActionCable adapter in different Rails environments. Litecable serves as a replacement for adapters like `async`, PostgreSQL, or Redis. ```yaml development: adapter: litecable test: adapter: test staging: adapter: litecable production: adapter: litecable ``` -------------------------------- ### Define and Include Litejob Module in Ruby Source: https://github.com/oldmoe/litestack/wiki/Litejob-guide This snippet demonstrates how to define a job class in Ruby, include the Litejob module, and specify a named queue. The `perform` method is where the actual job logic resides and can accept any number of parameters. ```ruby require 'litestack' class AddJob include Litejob # select which specific named queue your jobs should go to self.queue = 'my_job_queue' # perform must be implemented and can have any number of parameters def perform(a, b) a + b end end ``` -------------------------------- ### Direct Litecache Usage - Ruby Source: https://github.com/oldmoe/litestack/blob/master/README.md Provides an example of directly using Litecache, a high-speed caching library with an SQLite backend. It demonstrates how to initialize the cache, set a key-value pair, and retrieve the value. Litecache supports key expiry and LRU eviction. ```ruby require 'litestack' cache = Litecache.new(path: "path_to_file") cache.set("key", "value") cache.get("key") #=> "value" ``` -------------------------------- ### Interact with Specific Litequeues (Ruby) Source: https://github.com/oldmoe/litestack/wiki/Litequeue-Guide Demonstrates how to perform operations on specific queues within Litequeue. This involves passing the desired queue name as an argument to methods like 'push', 'pop', and 'count'. ```ruby # Adding to a specific queue queue.push("value", 0, "specificQueue") # Popping from a specific queue item = queue.pop("specificQueue") # Counting items in a specific queue count = queue.count("specificQueue") ``` -------------------------------- ### Capture Events with Keys in Ruby using Litemetric Source: https://github.com/oldmoe/litestack/wiki/litemetric-guide Illustrates capturing events with specific keys in Ruby using Litemetric. This allows for differentiating metrics based on provided keys, such as differentiating cache keys or queue names. Assumes Litestack is required. ```ruby class Ticker def change(symbol, value) capture("change", symbol, value) end end ``` -------------------------------- ### Sequel Database Integration with Litedb Source: https://context7.com/oldmoe/litestack/llms.txt Integrates Litedb with the Sequel database toolkit, demonstrating connection setup, schema creation, record insertion, and querying using Sequel's expressive syntax. It uses the `litedb://` protocol for connection. ```ruby require 'litestack' require 'sequel' # Connect using litedb:// protocol DB = Sequel.connect("litedb://./myapp.db") # Create table with Sequel schema DB.create_table :products do primary_key :id String :name, null: false Decimal :price, size: [10, 2] Integer :stock DateTime :created_at end # Insert records DB[:products].insert(name: "Widget", price: 19.99, stock: 100, created_at: Time.now) DB[:products].insert(name: "Gadget", price: 29.99, stock: 50, created_at: Time.now) # Query with Sequel's expressive syntax products = DB[:products].where { price < 25 }.all # => [{:id=>1, :name=>"Widget", :price=>19.99, :stock=>100, :created_at=>...}] low_stock = DB[:products].where { stock < 75 }.select(:name, :stock).all ``` -------------------------------- ### Capture and Measure Events in Ruby with Litemetric Source: https://github.com/oldmoe/litestack/wiki/litemetric-guide Demonstrates how to include the Litemetric::Measurable module in a Ruby class to capture and measure events. It shows overriding the metrics_identifier, capturing simple events, and measuring complex actions with runtime durations. Assumes Litestack is required. ```ruby class ImportantClass include Litemetric::Measurable # override the default identifier def metrics_identifier self.class.name end # the captured action will only be counted # the database will have a count of times the event was captured def simple # do something capture("simple") end # the measured action will also capture the runtime of the action # the database will have a count of times the event was measured and the total time measured def complex measure("complex") do # do something end end end ``` -------------------------------- ### Count Items in a Litequeue (Ruby) Source: https://github.com/oldmoe/litestack/wiki/Litequeue-Guide Returns the number of items currently in a Litequeue. The 'count' method can be used to get the total count across all queues or the count for a specific queue by providing its name. ```ruby total = queue.count # Count items in all queues specific_total = queue.count("myQueue") # Count items in "myQueue" ``` -------------------------------- ### Configure Rails ActiveJob Adapter for Litejob Source: https://github.com/oldmoe/litestack/wiki/Litejob-guide This Ruby code snippet shows how to configure Rails to use Litejob as its ActiveJob queue adapter. This integration allows developers to leverage Litejob's features seamlessly within a Rails application using the standard ActiveJob API. ```ruby config.active_job.queue_adapter = :litejob ``` -------------------------------- ### Delete Items from a Litequeue (Ruby) Source: https://github.com/oldmoe/litestack/wiki/Litequeue-Guide Removes a specific item from a Litequeue using its job ID. This operation is useful for discarding items before they are processed. ```ruby queue.delete(id) ``` -------------------------------- ### Clear Litequeues (Ruby) Source: https://github.com/oldmoe/litestack/wiki/Litequeue-Guide Removes all items from a Litequeue. The 'clear' method can be called without arguments to clear all queues or with a specific queue name to clear only that queue. ```ruby queue.clear # Clears all queues queue.clear("myQueue") # Clears items from "myQueue" only ``` -------------------------------- ### Enable Litemetric in Litestack Component Configuration Source: https://github.com/oldmoe/litestack/wiki/litemetric-guide Demonstrates how to enable Litemetric metric collection within the configuration files of other Litestack components like Litedb, Litejob, and Litecache. Setting `metrics: true` activates the collection of telemetry data for these components. ```yaml metrics: true # default is false ``` -------------------------------- ### Pop Items from a Litequeue (Ruby) Source: https://github.com/oldmoe/litestack/wiki/Litequeue-Guide Retrieves and removes the next item from a specified queue. The 'pop' method accepts an optional queue name (defaults to 'default') and an optional limit for the number of items to pop (defaults to 1). ```ruby item = queue.pop # By default, pops from the "default" queue item = queue.pop("myQueue") ``` -------------------------------- ### Capture Multiple Events/Keys Simultaneously in Ruby with Litemetric Source: https://github.com/oldmoe/litestack/wiki/litemetric-guide Shows how to capture or measure multiple events or keys in a single operation using Litemetric in Ruby. This is useful for scenarios like reporting aggregated metrics alongside specific ones, such as job enqueuing for all queues and a specific queue. Assumes Litestack is required. ```ruby # capture multiple events in one shot def enqueue(queue_name, job) # do the action capture("enqueue", ["all", queue_name]) end # also with measurement def perform(queue_name, job) measure(perform, ["all", queue_name]) do # do the action end end ``` -------------------------------- ### Litesearch Integration with ActiveRecord Source: https://github.com/oldmoe/litestack/blob/master/README.md Shows how to integrate Litesearch with ActiveRecord models for full-text search. It involves including `Litesearch::Model`, defining the search schema within the model, and then using the `search` method for querying. This example includes defining associations between `Author` and `Book` models. ```ruby class Author < ActiveRecord::Base has_many :books end class Book < ActiveRecord::Base belongs_to :author include Litesearch::Model litesearch do |schema| schema.fields [:title, :description] schema.field :author, target: 'authors.name' schema.tokenizer :porter end end Author.create(name: 'Adam A. Writer') Book.create(title: 'The biggest stunt', author_id: 1, description: 'a description') Book.search('author: writer').limit(1).all ``` -------------------------------- ### Litesearch Integration with Sequel Source: https://github.com/oldmoe/litestack/blob/master/README.md Illustrates the integration of Litesearch with Sequel models for full-text search functionality. Similar to the ActiveRecord example, it requires including `Litesearch::Model` and defining the search schema within the model class. Queries are performed using the `search` method, which integrates with Sequel's query interface. ```ruby class Author < Sequel::Model one_to_many :books end class Book < Sequel::Model many_to_one :author include Litesearch::Model litesearch do |schema| schema.fields [:title, :description] schema.field :author, target: 'authors.name' schema.tokenizer :porter end end Author.create(name: 'Adam A. Writer') Book.create(title: 'The biggest stunt', author_id: 1, description: 'a description') Book.search('author: writer').limit(1).all ``` -------------------------------- ### Add Items to a Litequeue (Ruby) Source: https://github.com/oldmoe/litestack/wiki/Litequeue-Guide Adds an item to a Litequeue. The 'push' method takes the value, an optional delay in seconds (defaults to 0), and an optional queue name (defaults to 'default'). It returns a unique job ID. The 'repush' method can be used to re-queue an existing job with potentially new value and delay. ```ruby id = queue.push("somevalue", 2) # The value will be ready to pop in 2 seconds queue.repush(id, "newvalue", 3) ``` -------------------------------- ### High-Speed Caching with Litecache Source: https://context7.com/oldmoe/litestack/llms.txt Shows how to initialize and use Litecache for high-performance caching. It covers basic set/get operations, setting custom expiry times, and batch operations like `set_multi` and `get_multi`. The cache can be configured with a specific path, size, and default expiry. ```ruby require 'litestack' # Initialize cache with custom options cache = Litecache.new( path: "./cache/myapp_cache.db", size: 256 * 1024 * 1024, # 256MB cache size expiry: 3600 # Default 1 hour expiry ) # Basic set and get operations cache.set("user:123", {name: "Alice", role: "admin"}) user = cache.get("user:123") # => {:name=>"Alice", :role=>"admin"} # Set with custom expiry (60 seconds) cache.set("session:abc", {token: "xyz789", user_id: 123}, 60) # Set multiple keys at once cache.set_multi({ "product:1" => {name: "Widget", price: 19.99}, "product:2" => {name: "Gadget", price: 29.99} }, 7200) # Get multiple keys products = cache.get_multi("product:1", "product:2") ``` -------------------------------- ### Initialize Litesearch Index Source: https://github.com/oldmoe/litestack/wiki/Litesearch-Guide Demonstrates how to initialize a Litedb instance and define a search index with specific fields, weights, and tokenizer settings. ```ruby require 'litestack/litedb' db = Litedb.new(":memory:") idx = db.search_index('email') do |schema| schema.fields [:sender, :receiver, :body] schema.field :subject, weight: 10 schema.tokenizer :porter end ``` -------------------------------- ### Configuring Litecable for ActionCable Source: https://context7.com/oldmoe/litestack/llms.txt Sets up the Litecable adapter within the cable.yml file to handle WebSocket Pub/Sub using SQLite. ```yaml production: adapter: litecable path: ./tmp/cable.sqlite3 expire_after: 5 listen_interval: 0.05 ``` -------------------------------- ### Configuring Litecache for Rails Source: https://context7.com/oldmoe/litestack/llms.txt Shows how to replace the default Rails cache store with Litecache in production environments. ```ruby Rails.application.configure do config.cache_store = :litecache, { path: Rails.root.join('tmp', 'cache', 'production_cache.db'), size: 512 * 1024 * 1024, expiry: 86400 } end ``` -------------------------------- ### Configure Litesearch Full-Text Indexing Source: https://context7.com/oldmoe/litestack/llms.txt Shows how to create and configure a search index in Litedb with field weighting and tokenization. This allows for complex searches including partial matches and multi-field queries. ```ruby require 'litestack/litedb' db = Litedb.new(":memory:") idx = db.search_index('documents') do |schema| schema.fields [:sender, :receiver, :body] schema.field :subject, weight: 10 schema.tokenizer :trigram end idx.add({sender: 'Kamal', receiver: 'Laila', subject: 'Are the girls awake?', body: 'I got them the new phones...'}) results = idx.search('kamal') ``` -------------------------------- ### Performing Cache Operations with Litecache Source: https://context7.com/oldmoe/litestack/llms.txt Demonstrates atomic operations, conditional setting, and general cache management using the Litecache interface. ```ruby cache.set_unless_exists("config:initialized", true, 86400) cache.set("page:views", 0) cache.increment("page:views", 1) cache.decrement("page:views", 2) cache.delete("session:abc") cache.prune(10) cache.clear ``` -------------------------------- ### Litedb Configuration for Sequel - Ruby Source: https://github.com/oldmoe/litestack/blob/master/README.md Illustrates how to integrate Litedb with the Sequel database toolkit in Ruby. This configuration allows developers to use Litedb as the backend for Sequel, enabling its advanced features while benefiting from Litestack's performance optimizations. ```ruby DB = Sequel.connect("litedb://path_to_db_file") ``` -------------------------------- ### Perform Point Read Database Operations Source: https://github.com/oldmoe/litestack/blob/master/BENCHMARKS.md Demonstrates point read operations using ActiveRecord and Sequel ORMs, resulting in a standard SQL SELECT statement. ```ruby Post.find(id) #ActiveRecord Post[id] #Sequel ``` ```sql SELECT * FROM posts WHERE id = ? ``` -------------------------------- ### Direct Litedb Usage - Ruby Source: https://github.com/oldmoe/litestack/blob/master/README.md Demonstrates direct usage of Litedb, a wrapper around SQLite3, for database operations. It shows how to initialize a database connection, create a table, insert data, and query records. Litedb is designed for concurrency and performance, inheriting functionalities from the SQLite3 gem. ```ruby require 'litestack' db = Litedb.new(path_to_db) db.execute("create table users(id integer primary key, name text)") db.execute("insert into users(name) values (?)", "Hamada") db.query("select count(*) from users") # => [[1]] ``` -------------------------------- ### Direct Litejob Usage in Ruby Source: https://github.com/oldmoe/litestack/blob/master/README.md Demonstrates how to directly use Litejob for asynchronous job processing in Ruby. This involves defining a job class including the Litejob module and then scheduling jobs using `perform_async`, `perform_at`, or `perform_after`. ```ruby require 'litestack' class MyJob include ::Litejob queue = :default def perform(params) # do stuff end end MyJob.perform_async(params) MyJob.perform_at(time, params) MyJob.perform_after(delay, params) ``` -------------------------------- ### Perform Searches and Counts Source: https://github.com/oldmoe/litestack/wiki/Litesearch-Guide Illustrates how to query the index using single or multi-term syntax, field-specific filtering, and pagination. Also shows how to retrieve hit counts for specific search criteria. ```ruby idx.search('Kamal') idx.search('kamal OR layla') idx.search('(subject: miss) AND body:("girl")') idx.search('kamal', limit:10, offset:1000) idx.count('kamal') ``` -------------------------------- ### Integrating Litejob with ActiveJob Source: https://context7.com/oldmoe/litestack/llms.txt Configures Rails to use Litejob as the queue adapter and demonstrates standard ActiveJob syntax for queuing and scheduling. ```ruby Rails.application.configure do config.active_job.queue_adapter = :litejob end class ReportGenerationJob < ApplicationJob queue_as :urgent def perform(user_id, report_type) # Logic here end end ReportGenerationJob.perform_later(1, 'monthly') ``` -------------------------------- ### Direct SQLite Database Usage with Litedb Source: https://context7.com/oldmoe/litestack/llms.txt Demonstrates direct interaction with the Litedb SQLite wrapper, including table creation, data insertion, querying, transactions, and schema information retrieval. It inherits from SQLite3::Database, allowing familiar methods. ```ruby require 'litestack' # Direct usage - inherits from SQLite3::Database db = Litedb.new("./myapp.db") # Create table and insert data db.execute("CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT, email TEXT)") db.execute("INSERT INTO users(name, email) VALUES (?, ?)", "Alice Johnson", "alice@example.com") db.execute("INSERT INTO users(name, email) VALUES (?, ?)", "Bob Smith", "bob@example.com") # Query with results result = db.query("SELECT * FROM users WHERE name LIKE ?", "Alice%") # => [["1", "Alice Johnson", "alice@example.com"]] # Count records count = db.query("SELECT COUNT(*) FROM users") # => [[2]] # Transaction support with immediate locking to avoid deadlocks db.transaction do db.execute("UPDATE users SET email = ? WHERE name = ?", "newemail@example.com", "Alice Johnson") db.execute("INSERT INTO users(name, email) VALUES (?, ?)", "Charlie Davis", "charlie@example.com") end # Check database size and schema info size_mb = db.size.to_f / (1024 * 1024) table_count = db.schema_object_count("table") index_count = db.schema_object_count("index") db.close ``` -------------------------------- ### Standalone Litesearch Index Creation and Usage Source: https://github.com/oldmoe/litestack/blob/master/README.md Demonstrates how to use Litesearch independently for full-text search capabilities with Litedb. It covers creating a search index with specified fields and tokenizers, adding documents, and performing searches on specific fields or all fields. ```ruby require 'litestack/litedb' db = Litedb.new(":memory:") idx = db.search_index('index_name') do |schema| schema.fields [:sender, :receiver, :body] schema.field :subject, weight: 10 schema.tokenizer :trigram end idx.add({sender: 'Kamal', receiver: 'Laila', subject: 'Are the girls awake?', body: 'I got them the new phones they asked for, are they awake?'}) idx.search('kamal') idx.search('subject: awa') ``` -------------------------------- ### Retrieve and Modify Existing Index Source: https://github.com/oldmoe/litestack/wiki/Litesearch-Guide Explains how to fetch an existing index instance from the database and modify its schema, including adjusting field weights and rebuilding the index. ```ruby # Retrieving index idx = db.search_index('email') # Modifying schema idx.modify do |schema| schema.fields [:sender, :body, :subject, :urgent] schema.fields :reciever, weight: 0 schema.tokenizer = :trigram schema.rebuild_on_modify true end ``` -------------------------------- ### Implement ChatChannel for Real-time Messaging Source: https://context7.com/oldmoe/litestack/llms.txt Defines an ActionCable channel to handle user subscriptions, message broadcasting, and rendering. It allows users to send messages to specific rooms and broadcasts updates to all connected clients. ```ruby class ChatChannel < ApplicationCable::Channel def subscribed stream_from "chat_#{params[:room_id]}" end def unsubscribed stop_all_streams end def speak(data) message = current_user.messages.create!(room_id: params[:room_id], content: data['message']) ActionCable.server.broadcast("chat_#{params[:room_id]}", message: render_message(message), user: current_user.username) end private def render_message(message) ApplicationController.renderer.render(partial: 'messages/message', locals: { message: message }) end end ``` -------------------------------- ### Asynchronous Job Processing with Litejob Source: https://context7.com/oldmoe/litestack/llms.txt Defines custom job classes using the Litejob mixin and demonstrates scheduling jobs for immediate or future execution. ```ruby class EmailJob include Litejob self.queue = :mailers def perform(params) puts "Sending email to #{params['email']}" end end EmailJob.perform_async({'email' => 'user@example.com'}) EmailJob.perform_in(300, {'email' => 'user@example.com'}) ``` -------------------------------- ### Perform Multi-Row Read Operations Source: https://github.com/oldmoe/litestack/blob/master/BENCHMARKS.md Shows how to fetch multiple records filtered by user ID with a limit constraint, applicable to both ActiveRecord and Sequel. ```ruby Post.where(user_id: id).limit(5) # ActiveRecord and Sequel ``` ```sql SELECT * FROM posts WHERE user_id = ? LIMIT 5 ``` -------------------------------- ### Integrate Litesearch with Sequel Source: https://context7.com/oldmoe/litestack/llms.txt Provides full-text search capabilities for Sequel models, allowing search operations to be chained with Sequel dataset filters and query methods. ```ruby class Book < Sequel::Model include Litesearch::Model litesearch do |schema| schema.fields [:title, :description] schema.field :author, target: 'authors.name' schema.tokenizer :porter end end books = Book.search('database').limit(5).all ``` -------------------------------- ### Perform Database Point Update Source: https://github.com/oldmoe/litestack/blob/master/BENCHMARKS.md Executes an update operation on a specific record identified by an ID, demonstrating syntax for ActiveRecord and Sequel. ```ruby Post.update(id, {updated_at: updated_at}) # ActiveRecord Post[id].update({updated_at: updated_at}) # Sequel ``` ```sql Update posts SET updated_at = ? WHERE id = ? ``` -------------------------------- ### Perform Full-Text Search Queries Source: https://github.com/oldmoe/litestack/wiki/Litesearch-Sequel-guide Execute search queries across individual models or multiple models using the search and search_all methods. These methods integrate directly with the Sequel query interface. ```ruby Book.search('author: penguin').limit(10).all Author.search('penguin').all # search all models, from any model Book.search_all('penguin', limit: 50) # search specific models, also from any model Book.search_all('penguin', models: [Author]) ``` -------------------------------- ### Litedb Configuration for ActiveRecord - YAML Source: https://github.com/oldmoe/litestack/blob/master/README.md Shows how to configure Litedb as the database adapter for an ActiveRecord application within the database.yml configuration file. This allows Rails applications to seamlessly use Litedb for their data persistence needs, leveraging its performance benefits. ```yaml adapter: litedb # normal sqlite3 configuration follows ``` -------------------------------- ### Broadcast Messages from Controllers Source: https://context7.com/oldmoe/litestack/llms.txt Demonstrates how to trigger ActionCable broadcasts from outside a channel, specifically within a standard Rails controller action after creating a record. ```ruby class MessagesController < ApplicationController def create @message = current_user.messages.create!(message_params) ActionCable.server.broadcast("chat_#{@message.room_id}", { type: 'new_message', message: @message.content, user: current_user.username, timestamp: @message.created_at.iso8601 }) head :ok end end ``` -------------------------------- ### Enable and Collect Metrics in Litestack Components (Ruby) Source: https://context7.com/oldmoe/litestack/llms.txt This snippet demonstrates how to enable metrics collection for Litestack components like Litedb, Litecache, and Litejob by setting the 'metrics: true' option in their respective configuration files. It also shows how to integrate custom metrics collection for non-Litestack classes using the Litemetric::Measurable module, including measuring specific operations. ```ruby # config/database.yml - Enable metrics for Litedb production: adapter: litedb database: db/production.sqlite3 metrics: true # config/litecache.yml - Enable metrics for Litecache path: ./tmp/cache.db metrics: true # config/litejob.yml - Enable metrics for Litejob path: ./tmp/queue.db metrics: true # Metrics are automatically stored in metrics.sqlite3 # Located in Litesupport.root folder # Custom metrics collection for non-Litestack classes require 'litestack/litemetric' class MyService include Litemetric::Measurable def initialize collect_metrics # Enable metrics for this instance end def process_data(data) measure('processing', 'process_data') do # Your processing logic sleep(rand(0.1..0.5)) data.transform end end end # Metrics can be viewed using Liteboard web interface # Run: liteboard -h for usage instructions # Example: liteboard --config config/database.yml # Or: liteboard --metrics-db tmp/metrics.sqlite3 # Liteboard provides visualizations for: # - Database: size, query counts, read/write ratio, slow queries # - Cache: size, hit/miss ratio, entry counts, popular keys # - Jobs: queue depths, processing times, success/failure rates # - Custom: Any metrics collected via Litemetric::Measurable ``` -------------------------------- ### Configure LiteCache with Rails Source: https://github.com/oldmoe/litestack/blob/master/README.md Integrates LiteCache as a caching solution within a Rails application by configuring the cache store in an environment file. LiteCache uses a background thread for cleanup, or a fiber if Fiber::Scheduler or Polyphony is detected. ```ruby config.cache_store = :litecache, {path: './path/to/your/cache/file'} ``` -------------------------------- ### Perform Index Maintenance Operations Source: https://github.com/oldmoe/litestack/wiki/Litesearch-Sequel-guide Use model class methods to perform lifecycle management on the underlying search index, including rebuilding, clearing, or dropping the index data. ```ruby Book.rebuild_index! Book.clear_index! Book.drop_index! ``` -------------------------------- ### Integrate Litesearch with ActiveRecord Source: https://context7.com/oldmoe/litestack/llms.txt Integrates full-text search into ActiveRecord models, supporting field mapping from associated tables and stemming-based tokenization. It enables seamless integration with existing ActiveRecord query methods like limit and includes. ```ruby class Book < ActiveRecord::Base include Litesearch::Model litesearch do |schema| schema.fields [:title, :description] schema.field :author, target: 'authors.name' schema.tokenizer :porter end end books = Book.search('author: writer').limit(10).all ``` -------------------------------- ### Rails ActiveRecord Integration with Litedb Source: https://context7.com/oldmoe/litestack/llms.txt Configures and utilizes Litedb as the database adapter within a Ruby on Rails application using ActiveRecord. Includes database.yml configuration and basic model usage for data manipulation. ```yaml # config/database.yml development: adapter: litedb database: db/development.sqlite3 pool: 5 timeout: 5000 production: adapter: litedb database: db/production.sqlite3 pool: 5 timeout: 5000 ``` ```ruby # app/models/user.rb class User < ActiveRecord::Base validates :email, presence: true, uniqueness: true end # Usage in Rails application User.create(name: "Alice", email: "alice@example.com") user = User.find_by(email: "alice@example.com") User.where("name LIKE ?", "A%").count # => 1 ``` -------------------------------- ### Manage Documents in Litesearch Source: https://github.com/oldmoe/litestack/wiki/Litesearch-Guide Covers CRUD operations for indexed documents, including adding, updating, removing specific entries, clearing all data, or dropping an entire index. ```ruby # Adding a document id = idx.add(sender: 'Kamal', receiver: 'Layla', subject: 'Miss you all', body: 'you and the girls') # Updating a document idx.add(id: 1, sender: 'Kamal', receiver: 'Layla', subject: 'Miss you all very much', body: 'you and the girls') # Removing documents idx.remove(1) idx.clear! idx.drop! ``` -------------------------------- ### Define Litesearch Index Schemas in Sequel Models Source: https://github.com/oldmoe/litestack/wiki/Litesearch-Sequel-guide Configure full-text search indexes within Sequel::Model classes using the litesearch block. This allows specifying fields, column weights, and custom field mappings for indexed content. ```ruby class Author < Sequel::Model one_to_many :books include Litesearch::Model litesearch do |schema| schema.field :name end end class Book < Sequel::Model many_to_one :author include Litesearch::Model litesearch do |schema| schema.fields [:publishing_year, :description] schema.field :title, weight: 5 schema.field :ISBN, col: :isbn_code schema.field :author, target: 'auhtors.name', col: :author_id schema.filter_column :indexed end end ``` -------------------------------- ### Perform full-text searches across models Source: https://github.com/oldmoe/litestack/wiki/Litesearch-ActiveRecord-Guide Execute search queries against individual models or perform cross-model searches. The search interface is integrated into ActiveRecord query methods. ```ruby Book.search('author: penguin').limit(10) Author.search('penguin') # Search multiple or all models Book.search_all('penguin', limit: 50) Book.search_all('penguin', models: [Author]) ``` -------------------------------- ### Define Litesearch schema in ActiveRecord models Source: https://github.com/oldmoe/litestack/wiki/Litesearch-ActiveRecord-Guide Configure models to include Litesearch and define indexed fields, weights, and mappings. This allows the library to track and index database changes automatically. ```ruby class Author < ActiveRecord::Base has_many :books include Litesearch::Model litesearch do |schema| schema.field :name end end class Book < ActiveRecord::Base belongs_to :author include Litesearch::Model litesearch do |schema| schema.fields [:publishing_year, :description] schema.field :title, weight: 5 schema.field :ISBN, col: :isbn_code schema.field :author, target: 'auhtors.name', col: :author_id schema.filter_column :indexed end end ``` -------------------------------- ### Modify and Manage Index Schemas Source: https://github.com/oldmoe/litestack/wiki/Litesearch-Sequel-guide Update existing search schemas by redefining the litesearch block within the model class. This allows adjusting weights, adding new fields, or updating targets. ```ruby class Book < Sequel::Model belongs_to :author belongs_to :publisher include Litesearch::Model litesearch do |schema| schema.fields [:publishing_year, :description] schema.field :title, weight: 1 schema.field :author, target: 'auhtors.name', col: :author_id schema.field :publisher, target: 'publishers.name' end end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.