### Ruby: _Interface Type Example Source: https://literal.fun/docs/built-in-types Provides an example of the _Interface type in Ruby, used to verify if an object responds to a specific set of methods. ```ruby _Interface(:name, :age) ``` -------------------------------- ### Ruby: _Integer Type Example with Range Constraint Source: https://literal.fun/docs/built-in-types Shows an example of the _Integer type in Ruby, demonstrating how to apply a range constraint to validate integer values. ```ruby _Integer(18..) ``` -------------------------------- ### Ruby: _String Type Example with Length Constraint Source: https://literal.fun/docs/built-in-types Illustrates the _String type in Ruby, showing how to apply constraints to string properties such as length. ```ruby _String(length: 5..15) ``` -------------------------------- ### Ruby: Define Empty String Literal Source: https://literal.fun/docs/example-types This snippet shows how to define a literal for an empty string. It is represented by an empty string literal `""`. ```ruby EmptyString = "" ``` -------------------------------- ### Ruby: Define Populated String Literal Source: https://literal.fun/docs/example-types This snippet defines a literal for a non-empty string. It uses the `_String` type with a length constraint of 1 or more characters. ```ruby PopulatedString = _String(length: 1..) ``` -------------------------------- ### Ruby: _Map Type Example with Key-Value Constraints Source: https://literal.fun/docs/built-in-types Demonstrates the _Map type in Ruby for validating hash-like structures. It specifies the expected types for keys and their corresponding values. ```ruby _Map(name: String, age: Integer) ``` -------------------------------- ### Ruby: _Float Type Example with Range Constraint Source: https://literal.fun/docs/built-in-types Illustrates the usage of the _Float type in Ruby, specifically applying a range constraint to ensure the float value falls within a specified interval. ```ruby _Float(10..20) ``` -------------------------------- ### Ruby: Define RGB Color Literal Source: https://literal.fun/docs/example-types This snippet defines a literal for an RGB color value as a tuple of three byte values (0-255). It uses `_Integer` for byte values and `_Tuple` to group them. ```ruby ByteValueInt = _Integer(0..255) RGBColor = _Tuple(ByteValueInt, ByteValueInt, ByteValueInt) ``` -------------------------------- ### Ruby: Define Email Address String Literal Source: https://literal.fun/docs/example-types This snippet defines a literal that matches most valid email addresses using a regular expression. It leverages Ruby's `URI::MailTo::EMAIL_REGEXP`. ```ruby EmailAddressString = _String(URI::MailTo::EMAIL_REGEXP) ``` -------------------------------- ### Ruby: Define Adult Age Literal Source: https://literal.fun/docs/example-types This snippet defines a literal for an adult age, constrained to integers between 18 and 122 (inclusive). It uses the `_Integer` type with a specified range. ```ruby AdultAge = _Integer(18..122) ``` -------------------------------- ### Ruby: Define Human Age Literal Source: https://literal.fun/docs/example-types This snippet defines a literal for a human age, constrained to integers between 0 and 122 (inclusive). It uses the `_Integer` type with a specified range. ```ruby HumanAge = _Integer(0..122) ``` -------------------------------- ### Ruby: _Constraint Type Example Source: https://literal.fun/docs/built-in-types Demonstrates how to use the _Constraint type in Ruby to validate an object against a specific class and its associated method return types. It checks if an object is an instance of `Person` and if its `name` method returns a `String`. ```ruby _Constraint(Person, name: String) ``` -------------------------------- ### Access Literal Enum members and values in Ruby Source: https://literal.fun/docs/enums These examples show how to retrieve all members and their associated values from a defined enum. The `members` method returns a Set of enum instances, while `values` returns an Array of their corresponding values. ```ruby Color.members # => [Color::Red, Color::Green, Color::Blue] ``` ```ruby Color.values # => [1, 2, 3] ``` -------------------------------- ### Define properties on a Literal Enum in Ruby Source: https://literal.fun/docs/enums This example shows how to define custom properties on enum members, similar to other Literal objects. Properties are defined using `prop` and can be assigned values when creating new enum members. ```ruby class Color < Literal::Enum(Integer) prop :hex, String Red = new(1, hex: "FF0000") Green = new(2, hex: "00FF00") Blue = new(3, hex: "0000FF") end ``` -------------------------------- ### Ruby: Define Numeric Constraint Literals Source: https://literal.fun/docs/example-types This snippet defines various numeric literals including positive/negative integers/floats, numeric constraints, and specific unsigned/signed integer types (UInt8, Int16, etc.). It utilizes `_Integer`, `_Float`, and `_Constraint` with range specifications. ```ruby PositiveInteger = _Integer(1..) NegativeInteger = _Integer(..-1) PositiveFloat = _Float(1..) NegativeFloat = _Float(..-1) PositiveNumeric = _Constraint(Numeric, 1..) NegativeNumeric = _Constraint(Numeric, ..-1) UInt8 = _Integer(0..(2**8)) UInt16 = _Integer(0..(2**16)) UInt32 = _Integer(0..(2**32)) UInt64 = _Integer(0..(2**64)) Int8 = _Integer(-(2**7)..(2**7)-1) Int16 = _Integer(-(2**15)..(2**15)-1) Int32 = _Integer(-(2**31)..(2**31)-1) Int64 = _Integer(-(2**63)..(2**63)-1) ``` -------------------------------- ### Iterate over Literal Enum members in Ruby Source: https://literal.fun/docs/enums Since Literal enums are Enumerable, this example illustrates how to iterate over all members using the `each` method. Inside the loop, you can access properties like the member's name. ```ruby Color.each do |color| puts color.name end ``` -------------------------------- ### Define User Struct with Literal::Struct - Ruby Source: https://literal.fun/docs/structured-objects Example of defining a User class inheriting from Literal::Struct, specifying property types and constraints. Literal::Struct is mutable. ```ruby class User < Literal::Struct prop :name, String prop :age, _Integer(13..) end ``` -------------------------------- ### Define Properties with Types in Ruby Source: https://literal.fun/docs/properties Demonstrates defining basic properties with names and types using Literal::Properties. This adds an initializer with keyword arguments for the defined properties. ```ruby class Person extend Literal::Properties prop :name, String prop :age, Integer end ``` -------------------------------- ### Create Initialized Literal Array (Ruby) Source: https://literal.fun/docs/array Shows how to initialize a Literal::Array with a set of existing elements. The type of these initial elements must match the specified generic type (String). ```ruby array = Literal::Array(String).new("Hello", "World") ``` -------------------------------- ### Define Different Argument Types for Properties in Ruby Source: https://literal.fun/docs/properties Shows how to define properties that accept different kinds of arguments, including positional, positional rest, keyword rest, and blocks using Literal::Properties. ```ruby prop :name, String, :positional prop :names, _Array(String), :* prop :options, _Hash(Symbol, String), :** prop :block, Proc, :& ``` -------------------------------- ### Index Literal Enums by value and with blocks in Ruby Source: https://literal.fun/docs/enums This demonstrates how to set up indexing for enums, enabling efficient lookups. Indexes can be based on properties (like `hex`) or custom logic defined in a block, with options for uniqueness. ```ruby class Color < Literal::Enum(Integer) prop :hex, String # Index by value index :hex, String, unique: true # Index with a block index :lower_hex, String, unique: true do |color| color.hex.downcase end Red = new(1, hex: "FF0000") Green = new(2, hex: "00FF00") Blue = new(3, hex: "0000FF") def rgb hex.scan(/.{2}/).map { |it| it.to_i(16) } end end ``` -------------------------------- ### Default Values for Properties in Ruby Source: https://literal.fun/docs/properties Shows how to assign default values to properties. Defaults can be `Proc` objects (for dynamic defaults) or frozen objects (for static defaults). ```ruby prop :first_name, String, default: -> { "John" } prop :last_name, String, default: "Doe".freeze ``` -------------------------------- ### Optional Properties in Ruby Source: https://literal.fun/docs/properties Explains how to define optional properties by using `_Nilable` for the type. If a property's type is `_Nilable`, it can accept `nil` and is considered optional. ```ruby prop :name, _Nilable(String) ``` -------------------------------- ### Create Empty Literal Array (Ruby) Source: https://literal.fun/docs/array Demonstrates how to create an empty Literal::Array that will hold elements of a specified type (String in this case). This ensures type safety from the outset. ```ruby array = Literal::Array(String).new ``` -------------------------------- ### Attribute Accessors for Properties in Ruby Source: https://literal.fun/docs/properties Demonstrates how to specify attribute readers and writers for properties using the `reader` and `writer` options. Accessors can be set to public, protected, or private. ```ruby prop :name, String, reader: :public, writer: :protected ``` -------------------------------- ### Type Coercion for Properties in Ruby Source: https://literal.fun/docs/properties Illustrates how to use a block with `prop` to coerce values to the correct type before they are type-checked or assigned. This is useful for conversions like strings to integers. ```ruby prop :age, Integer do |value| value.to_i end ``` -------------------------------- ### Define a Data Object with Properties in Ruby Source: https://literal.fun/docs/index This Ruby code defines a `Name` data object using Literal. It specifies `first` and `last` properties as non-empty strings and includes a `full` method to concatenate them. It relies on the Literal gem for data object definition and validation. ```ruby class Name < Literal::Data prop :first, _String(length: 1..) prop :last, _String(length: 1..) def full "#{@first} #{@last}" end end ``` -------------------------------- ### Map Literal Array with Symbol Proc (Ruby) Source: https://literal.fun/docs/array Demonstrates an optimized mapping scenario using a Symbol proc. When Literal can infer the return type of the proc (e.g., String#length always returns an Integer), it may skip explicit type checks for performance. ```ruby array = Literal::Array(String).new("Hello", "World") mapped = array.map(Integer, &:length) ``` -------------------------------- ### Map Literal Array with Type Specification (Ruby) Source: https://literal.fun/docs/array Illustrates mapping elements of a Literal::Array to a new type. The target type for the new array must be explicitly provided during the map operation. Type errors during mapping will raise a Literal::TypeError. ```ruby array = Literal::Array(String).new("Hello", "World") mapped = array.map(Integer) do |it| it.length * 10 end ``` -------------------------------- ### Define ActiveRecord Relations with Literal Properties Source: https://literal.fun/docs/rails Demonstrates how to use Literal's `prop` to define an ActiveRecord::Relation property within a Rails component. This requires the `literal` gem and a Rails environment. ```ruby class Components::ArticlesList < Components::Base extend Literal::Properties prop :articles, ActiveRecord::Relation(Article) end ``` -------------------------------- ### Ruby Array Element Type Checking with 'all?' and 'any?' Source: https://literal.fun/docs/types Shows how Ruby's `Array#all?` and `Array#any?` methods use the `===` operator to efficiently check if all or any elements in an array conform to a given type. This provides a concise way to validate array contents. ```ruby [1, 2, 3].all?(String) # false [1, 2, 3].all?(Integer) # true [1, "2", 3].any?(String) # true [1, "2", 3].any?(Integer) # true ``` -------------------------------- ### Ruby Case Statement Type Matching Source: https://literal.fun/docs/types Demonstrates how Ruby's `case` statement utilizes the `===` method of each `when` clause to determine a match with the evaluated expression. This showcases a core application of literal types. ```ruby case 42 when String puts "It's a string!" when Integer puts "It's an integer!" end ``` -------------------------------- ### Define instance methods for Literal Enum members in Ruby Source: https://literal.fun/docs/enums You can define instance methods directly within the enum class, making them available to all enum members. This allows for custom logic to be associated with each enum constant. ```ruby class Color < Literal::Enum(Integer) prop :hex, String Red = new(1, hex: "FF0000") Green = new(2, hex: "00FF00") Blue = new(3, hex: "0000FF") def rgb hex.scan(/.{2}/).map { |it| it.to_i(16) } end end ``` -------------------------------- ### Query Literal Enums using `where` and `find_by` in Ruby Source: https://literal.fun/docs/enums With indexing configured, you can use `where` for multi-match queries and `find_by` for unique-match queries on enum members. This allows for data retrieval based on indexed properties or computed values. ```ruby Color.where(lower_hex: "0000ff") # => [Color::Blue] ``` ```ruby Color.find_by(lower_hex: "0000ff") # => Color::Blue ``` -------------------------------- ### Access Literal Enum instance methods in Ruby Source: https://literal.fun/docs/enums These snippets demonstrate accessing instance methods of an enum member. The `value` method returns the underlying value associated with the enum member, and the `name` method returns its fully qualified name. ```ruby Color::Red.value # => 1 ``` ```ruby Color::Red.name # => "Color::Red" ``` -------------------------------- ### Match Any Type with _Union (Ruby) Source: https://literal.fun/docs/built-in-types The _Union function matches if any of the provided types match the input. This is useful for handling data that can be one of several expected types, such as strings or symbols. ```ruby _Union(String, Symbol) ``` -------------------------------- ### Define a basic Literal Enum in Ruby Source: https://literal.fun/docs/enums This snippet demonstrates how to define a simple enum named 'Color' with integer values. It requires specifying each value manually to ensure proper serialization and prevent order-related issues. ```ruby class Color < Literal::Enum(Integer) Red = new(1) Green = new(2) Blue = new(3) end ``` -------------------------------- ### Using Generated Generic Types in Ruby Source: https://literal.fun/docs/types Demonstrates how to use the custom generic type generator function `_Array` with specific types (e.g., `String`, `Integer`) to create and apply type checks to array instances. This highlights the flexibility of generic type creation. ```ruby _Array(String) === [1, 2, 3] # false _Array(Integer) === [1, 2, 3] # true ``` -------------------------------- ### Ruby Class Type Checking with '===' Source: https://literal.fun/docs/types Demonstrates how Ruby classes use the `===` operator to check if an object is an instance of the class or a subclass. This is a fundamental way Ruby defines types. ```ruby String === "Hello" # => true String === 42 # => false ``` -------------------------------- ### Ruby Pattern Matching with Type Checking Source: https://literal.fun/docs/types Illustrates Ruby's pattern matching capabilities, specifically within `case` statements, where types are used to deconstruct and match complex data structures. This extends type checking to nested elements. ```ruby case [42] in Array[String] puts "It's a string in an array!" in Array[Integer] puts "It's an integer in an array!" end ``` -------------------------------- ### Always Match with _Void (Ruby) Source: https://literal.fun/docs/built-in-types The _Void function always matches, serving as the opposite of _Never. It is used in scenarios where a match is guaranteed, irrespective of the input type. -------------------------------- ### Ruby Object Equivalence Check with '===' Source: https://literal.fun/docs/types Illustrates how typical Ruby objects use the `===` operator as an alias for `==` to check for object equivalence. This is useful for direct value comparisons. ```ruby "Hello" === "Hello" # => true "Hello" === "World" # => false ``` -------------------------------- ### Ruby Proc Type Checking with 'call' via '===' Source: https://literal.fun/docs/types Explains that Procs in Ruby alias `===` to their `call` method, allowing them to be used as types for conditional logic. This enables functional-style type checking. ```ruby is_even = proc { |it| it % 2 == 0 } is_even === 42 # => true is_even === 21 # => false ``` -------------------------------- ### Cast values to Literal Enum members in Ruby Source: https://literal.fun/docs/enums This shows how to retrieve an enum member by its associated value using either the array-like access `[]` or the `cast` method. Both achieve the same result of mapping a value back to its enum constant. ```ruby Color[1] # => Color::Red Color.cast(2) # => Color::Green ``` -------------------------------- ### Configure Literal Enum for Multiple Values in ActiveRecord Source: https://literal.fun/docs/rails Explains how to configure a Literal enum attribute in ActiveRecord to accept an array of values by setting `array: true`. Ensure the database column supports array types. ```ruby attribute :status, :literal_enum, type: Status, array: true ``` -------------------------------- ### Ruby Range Type Checking with '===' Source: https://literal.fun/docs/types Shows how the `===` operator on a Ruby Range checks if a given object falls within the specified range (inclusive). This is a specialized use of `===` for range boundaries. ```ruby (1..10) === 5 # => true (1..10) === 15 # => false ``` -------------------------------- ### Use automatic identity predicates for Literal Enums in Ruby Source: https://literal.fun/docs/enums Literal enums automatically generate predicate methods based on member names. This allows for easy boolean checks to determine if a given enum instance matches a specific member. ```ruby color = Color::Red color.red? # => true color.green? # => false ``` -------------------------------- ### Ruby Generic Type Generator Function Source: https://literal.fun/docs/types Presents a Ruby method `_Array` that acts as a generic function to create parameterized types (Procs in this case). It generates a type checker for arrays that verifies both the array structure and the types of its elements. ```ruby def _Array(type) proc { |it| Array === it && it.all?(type) } end ``` -------------------------------- ### Use Literal Enums as ActiveRecord Attributes Source: https://literal.fun/docs/rails Shows how to define a Literal enum and use it as an attribute type in an ActiveRecord model, replacing Rails' default enum implementation. Requires the `literal` gem. ```ruby class Article < ApplicationRecord class Status < Literal::Enum(Integer) Draft = new(1) Published = new(2) end attribute :status, :literal_enum, type: Status end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.