### Setup development dependencies for rbs-inline Source: https://github.com/soutaro/rbs-inline/blob/main/README.md This command is used in the development environment of the `rbs-inline` gem to install necessary dependencies. It is part of the setup process after cloning the repository. ```shell bin/setup ``` -------------------------------- ### Install rbs-inline gem locally Source: https://github.com/soutaro/rbs-inline/blob/main/README.md Command to install the `rbs-inline` gem from the local development version onto the machine. This is useful for testing the gem as if it were installed from a gem source. ```shell bundle exec rake install ``` -------------------------------- ### Struct.new with Keyword Initialization Options Source: https://github.com/soutaro/rbs-inline/wiki/Data-Struct-support This example illustrates how RBS::Inline handles the `keyword_init:` option in `Struct.new` calls. It shows the Ruby code defining a struct and explains how the generated RBS differs based on whether `keyword_init` is true, false, or another literal. ```ruby # @rbs %a{rbs-inline:new-args=required} # @rbs %a{rbs-inline:readonly-attributes=true} Group = Struct.new( :accounts #: Array[Account] ) ``` -------------------------------- ### Path Calculation for Output Files (Ruby) Source: https://context7.com/soutaro/rbs-inline/llms.txt This Ruby example demonstrates how to use `RBS::Inline::CLI::PathCalculator` to determine the correct output paths for generated RBS files based on project structure. It takes the current working directory, base paths, and the output directory as input. ```ruby require "rbs/inline/cli" require "pathname" # Calculate output paths relative to base paths calculator = RBS::Inline::CLI::PathCalculator.new( Pathname("/project"), # pwd [Pathname("lib"), Pathname("app")], # base_paths Pathname("/project/sig/generated") # output_path ) # Calculate output path for a Ruby file input_path = Pathname("/project/lib/models/user.rb") output_path = calculator.calculate(input_path) # => # input_path = Pathname("/project/app/controllers/users_controller.rb") output_path = calculator.calculate(input_path) # => # ``` -------------------------------- ### Start an interactive console for rbs-inline Source: https://github.com/soutaro/rbs-inline/blob/main/README.md This command launches an interactive Ruby console pre-loaded with the `rbs-inline` gem's environment. It allows developers to experiment with the gem's functionality directly. ```shell bin/console ``` -------------------------------- ### Install rbs-inline gem using Bundler Source: https://github.com/soutaro/rbs-inline/blob/main/README.md Command to install the `rbs-inline` gem using Bundler and add it to the application's `Gemfile`. The `--require=false` flag is crucial for ensuring that the gem's type definitions do not interfere with the application's runtime dependencies. ```shell $ bundle add rbs-inline --require=false ``` -------------------------------- ### Install rbs-inline gem without Bundler Source: https://github.com/soutaro/rbs-inline/blob/main/README.md Command to install the `rbs-inline` gem using the standard RubyGems command. This is an alternative to using Bundler for managing gem installations. ```shell $ gem install rbs-inline ``` -------------------------------- ### Workaround for Steep Compatibility with Data Definitions Source: https://github.com/soutaro/rbs-inline/wiki/Data-Struct-support This example demonstrates a workaround for potential type errors when using `Data.define` with Steep. It uses the `__skip__` annotation to bypass type checking for the `Data` definition, allowing custom methods to be defined in a separate class block. ```ruby Account = __skip__ = Data.define( :id, #: Integer :email #: String ) class Account # @rbs (String) -> void def send_email(body) # Do something end end ``` -------------------------------- ### Advanced Parameter Annotations in Ruby Source: https://context7.com/soutaro/rbs-inline/llms.txt Demonstrates how to use rbs-inline annotations for various parameter types including splat, optional, and keyword parameters. These annotations help define the expected types for method arguments and return values. ```ruby # rbs_inline: enabled class Processor # Splat parameters # @rbs *args: String # @rbs **options: untyped # @rbs &block: (String) -> void # @rbs return: void def process(*args, **options, &block) args.each(&block) end # Optional and keyword parameters # @rbs a: Integer # @rbs b: Integer # @rbs c: String # @rbs return: String def format(a, b = 10, c:) "#{c}: #{a + b}" end end ``` -------------------------------- ### Process Files with CLI Programmatically (Ruby) Source: https://context7.com/soutaro/rbs-inline/llms.txt This Ruby snippet shows how to programmatically invoke the `rbs-inline` CLI tool. It demonstrates initializing the CLI, defining arguments for processing files, and checking the exit code. Verbose logging can also be enabled. ```ruby require "rbs/inline/cli" # Create CLI instance cli = RBS::Inline::CLI.new(stdout: STDOUT, stderr: STDERR) # Process files args = [ "--output=sig/generated", "--base=lib", "--base=app", "--unknown-type=Object", "lib/", "app/" ] exit_code = cli.run(args) # Returns 0 on success # Enable verbose logging cli.logger.level = :DEBUG ``` -------------------------------- ### Inline Data and Struct Type Annotations in Ruby Source: https://context7.com/soutaro/rbs-inline/llms.txt This Ruby code demonstrates inline type annotations for `Data.define` and `Struct.new` using RBS::Inline. It covers `Data.define` with attribute types, `Struct.new` with keyword initialization and options like `readonly-attributes` and `new-args`, and `Struct.new` with positional initialization. ```ruby # rbs_inline: enabled # Data.define with attribute types User = Data.define( :id, #: Integer :name, #: String :email #: String ) # Struct with keyword initialization # @rbs %a{rbs-inline:readonly-attributes=true} # @rbs %a{rbs-inline:new-args=required} Point = Struct.new(:x, :y, keyword_init: true) do #: Integer #: Integer end # Struct with positional initialization Pair = Struct.new(:first, :second) do #: String #: Integer end ``` -------------------------------- ### Handle Mixins in RBS Source: https://github.com/soutaro/rbs-inline/wiki/Syntax-guide Mixin method calls like 'include', 'prepend', and 'extend' with constant syntax are translated to RBS mixin syntax. The '#[' syntax allows for generic modules. ```ruby class Foo include Foo extend Enumerable #[Integer, void] end ``` -------------------------------- ### Inline Method Type Annotations in Ruby Source: https://context7.com/soutaro/rbs-inline/llms.txt This snippet demonstrates various ways to annotate method types directly within Ruby code using RBS::Inline syntax. It covers full method signatures with `@rbs`, short syntax with `#:`, separate parameter and return types, methods with blocks, multiple overloads, and overriding parent methods. ```ruby # rbs_inline: enabled class Calculator # Full method type with @rbs # @rbs (Integer, Integer) -> Integer def add(a, b) a + b end # Short syntax with #: #: (Integer, Integer) -> Integer def subtract(a, b) a - b end # Parameter and return type separately # @rbs a: Integer # @rbs b: Integer # @rbs return: Integer def multiply(a, b) a * b end # Method with block # @rbs &block: (Integer) -> void def each_number(&block) #: void [1, 2, 3].each(&block) end # Multiple overloads # @rbs (Integer) -> String # @rbs (String) -> Integer def convert(value) value.is_a?(Integer) ? value.to_s : value.to_i end # Override parent method # @rbs override def to_s "Calculator" end end ``` -------------------------------- ### Calculate RBS Path for Input File (Ruby) Source: https://context7.com/soutaro/rbs-inline/llms.txt Demonstrates how RBS::Inline calculates the output RBS file path based on an input Ruby file path. It handles cases where the input file is within the project's base path and when it's outside. ```ruby input_path = Pathname("/project/config/initializer.rb") output_path = calculator.calculate(input_path) # => # input_path = Pathname("/other/file.rb") output_path = calculator.calculate(input_path) # => nil ``` -------------------------------- ### Method Annotations with RBS in Ruby Source: https://github.com/soutaro/rbs-inline/wiki/Syntax-guide Allows adding annotations to methods, such as 'pure' or custom ones, using the `%a{}` syntax. This is useful for documenting method properties directly in the code. ```ruby # @rbs %a{pure} %a{another:annotation} def to_s #: String end ``` -------------------------------- ### Generate RBS Output from Declarations (Ruby) Source: https://context7.com/soutaro/rbs-inline/llms.txt This Ruby code demonstrates how to use `rbs-inline` to generate RBS signature files from parsed Ruby code declarations. It covers creating a writer, adding header comments, writing declarations, and customizing default types. ```ruby require "rbs/inline" # Assuming you have parsed declarations uses, decls, rbs_decls = RBS::Inline::Parser.parse(result, opt_in: true) # Create writer and generate RBSwriter = RBS::Inline::Writer.new # Add header commentswriter.header("Generated from lib/calculator.rb with RBS::Inline") # Write declarations to RBS formatwriter.write(uses, decls, rbs_decls) # Get generated RBS content rbs_content = writer.output puts rbs_content # Customize default type for untyped parameterswriter.default_type = RBS::Types::Bases::Top.new(location: nil) # Write to file File.write("sig/calculator.rbs", writer.output) ``` -------------------------------- ### Automate RBS file generation with fswatch and rbs-inline Source: https://github.com/soutaro/rbs-inline/blob/main/README.md This command pipeline combines `fswatch` to monitor file changes in the `lib` directory with `xargs` and `bundle exec rbs-inline` to automatically regenerate RBS files whenever the source Ruby code is modified. This provides a continuous type checking workflow. ```shell $ fswatch -0 lib | xargs -0 -n1 bundle exec rbs-inline --output ``` -------------------------------- ### Run tests for rbs-inline gem Source: https://github.com/soutaro/rbs-inline/blob/main/README.md This command executes the test suite for the `rbs-inline` gem. It is used during development to ensure the correctness of the code. ```shell rake test ``` -------------------------------- ### VSCode Ruby Snippets for RBS::Inline Source: https://github.com/soutaro/rbs-inline/wiki/Snippets A collection of VSCode user snippets designed to facilitate the use of RBS::Inline in Ruby projects. These snippets allow for quick insertion of type annotations and declarations directly within the editor. They are scoped to Ruby files and triggered by specific prefixes. ```json { "Magic comment": { "scope": "ruby", "prefix": "rbs_inline: enabled", "body": [ "rbs_inline: enabled" ], "description": "Enable RBS::Inline" }, "Method parameter type": { "scope": "ruby", "prefix": "@rbs {variable}: {T}", "body": [ "@rbs ${1:variable}: ${2:type}" ], "description": "Type of method parameter" }, "Method return type": { "scope": "ruby", "prefix": "@rbs return: {T}", "body": [ "@rbs return: ${1:type}" ], "description": "Return type of a method" }, "Block type": { "scope": "ruby", "prefix": "@rbs &{block}: () -> T", "body": [ "@rbs &${1:block}: ${2:method-type}" ], "description": "Type of a block parameter" }, "Splat parameter type": { "scope": "ruby", "prefix": "@rbs *{args}: T", "body": [ "@rbs *${1:args}: ${2:type}" ], "description": "Type of a splat parameter" }, "Double splat parameter type": { "scope": "ruby", "prefix": "@rbs **{opts}: T", "body": [ "@rbs **${1:opts}: ${2:type}" ], "description": "Type of a splat parameter" }, "`use` directive": { "scope": "ruby", "prefix": "@rbs use {Clause}", "body": [ "@rbs use ${1:clause}" ], "description": "`use` directive" }, "super_class": { "scope": "ruby", "prefix": "@rbs inherits {T}", "body": [ "@rbs inherits ${1:super-class}" ], "description": "Define super class of a class definition" }, "module-self": { "scope": "ruby", "prefix": "@rbs module-self {T}", "body": [ "@rbs module-self ${1:self-type}" ], "description": "Define module-self constraint of a module definition" }, "generics": { "scope": "ruby", "prefix": "@rbs generic {A}", "body": [ "@rbs generic ${1:type parameter}" ], "description": "Define generics type parameter of a class/module definition" }, "ivar": { "scope": "ruby", "prefix": "@rbs @{instance_variable}: {type}", "body": [ "@rbs @${1:x}: ${2:type}" ], "description": "Define type of instance variables" }, "selfivar": { "scope": "ruby", "prefix": "@rbs self.@{instance_variable}: {type}", "body": [ "@rbs self.@${1:x}: ${2:type}" ], "description": "Define type of instance variables" }, "inline": { "scope": "ruby", "prefix": "@rbs!", "body": [ "@rbs!", "$LINE_COMMENT " ], "description": "Embed any RBS declarations" }, "skip": { "scope": "ruby", "prefix": "@rbs skip", "body": [ "@rbs skip" ], "description": "Skip following definition" }, "override": { "scope": "ruby", "prefix": "@rbs override", "body": [ "@rbs override" ], "description": "Override existing definition" }, "annotation": { "scope": "ruby", "prefix": "@rbs %a{}", "body": ["@rbs %a{${1}}"], "description": "Insert RBS annotation" }, "module-decl": { "scope": "ruby", "prefix": "@rbs module {M}", "body": ["@rbs module ${1:module-name}"], "description": "Module declaration" }, "class-decl": { "scope": "ruby", "prefix": "@rbs class {C}", "body": ["@rbs class ${1:module-name}"], "description": "Class declaration" } } ``` -------------------------------- ### Generate RBS Files with RBS::Inline CLI Source: https://context7.com/soutaro/rbs-inline/llms.txt The RBS::Inline command-line interface generates RBS files from annotated Ruby code. Options include specifying output directories, enabling opt-out mode, defining base paths for relative calculations, customizing unknown types, enabling verbose logging, and watching for file changes. ```bash # Print generated RBS to stdout rbs-inline lib/ # Save generated RBS files to sig/generated directory rbs-inline --output lib/ # Save to custom directory rbs-inline --output=types lib/ # Use opt-out mode (generate for all files except those with `# rbs_inline: disabled`) rbs-inline --opt-out --output lib/ # Specify base paths for relative path calculation rbs-inline --base=lib --base=app --output lib/ app/ # Use custom unknown type instead of 'untyped' rbs-inline --unknown-type=Object --output lib/ # Enable verbose logging rbs-inline --verbose --output lib/ # Watch for changes and regenerate (requires fswatch) fswatch -0 lib | xargs -0 -n1 rbs-inline --output ``` -------------------------------- ### Parse Ruby Code and Extract Type Declarations (Ruby) Source: https://context7.com/soutaro/rbs-inline/llms.txt This Ruby code snippet demonstrates how to use the `rbs-inline` and `prism` gems to parse a Ruby file and extract type declarations. It shows both opt-in and opt-out modes for parsing and how to process the extracted declarations. ```ruby require "rbs/inline" require "prism" # Parse a Ruby file with inline annotations result = Prism.parse_file("lib/calculator.rb") # Extract type declarations (opt-in mode) uses, decls, rbs_decls = RBS::Inline::Parser.parse(result, opt_in: true) # uses: Array of @rbs use directives # decls: Array of AST::Declarations (classes, modules, constants) # rbs_decls: Array of embedded RBS declarations from @rbs! # Returns nil if file lacks `# rbs_inline: enabled` in opt-in mode if uses && decls puts "Found #{uses.size} use directives" puts "Found #{decls.size} declarations" decls.each do |decl| case decl when RBS::Inline::AST::Declarations::ClassDecl puts "Class: #{decl.class_name}" when RBS::Inline::AST::Declarations::ModuleDecl puts "Module: #{decl.module_name}" end end end # Opt-out mode (process all files except those with `# rbs_inline: disabled`) uses, decls, rbs_decls = RBS::Inline::Parser.parse(result, opt_in: false) ``` -------------------------------- ### Generate RBS files from Ruby code using rbs-inline CLI Source: https://github.com/soutaro/rbs-inline/blob/main/README.md These shell commands demonstrate how to use the `rbs-inline` command-line interface to generate RBS files from annotated Ruby source code. The first command prints the generated RBS to standard output, while the second saves the generated files to a specified output directory. ```shell # Print generated RBS files $ bundle exec rbs-inline lib # Save generated RBS files under sig/generated $ bundle exec rbs-inline --output lib ``` -------------------------------- ### Inline Instance and Class Variable Annotations in Ruby Source: https://context7.com/soutaro/rbs-inline/llms.txt This Ruby code snippet shows how to annotate instance and class variables using RBS::Inline. It demonstrates annotating instance variables (`@count`) and class variables (`self.@total`) with their respective types. ```ruby # rbs_inline: enabled class Counter # @rbs @count: Integer # @rbs self.@total: Integer def initialize #: void @count = 0 self.class.instance_variable_set(:@total, 0) end #: () -> Integer def increment @count += 1 end end ``` -------------------------------- ### Define Method Types with Doc Style Syntax Source: https://github.com/soutaro/rbs-inline/wiki/Syntax-guide The doc style syntax uses '# @rbs param: TYPE -- comment' for parameter types and '# @rbs return: TYPE' for return types. Block types are defined with '# @rbs &block:' or '# @rbs &:' annotations. ```ruby # @rbs size: Integer -- The size of the section in px # @rbs optional: Integer -- Type of the optional parameter # @rbs title: String -- Title of the section # @rbs content: String -- Type of the optional keyword parameter # @rbs *rest: String -- Type of the rest args # @rbs **kwrest: untyped -- Type of the keyword rest args # @rbs return: Section? -- Returns the new section or `nil` def section(size, optional=123, title:, content: "Hello!", *rest, **kwrest) end ``` ```ruby # @rbs &block: (?) -> untyped -- Block is required, but not clear what will be yielded def foo(&block) yield 1 yield 2, "true" end # @rbs &block: ? (?) -> untyped -- Block is optional def bar(&block) end # @rbs &: (String) -> void -- It yields String def baz end ``` ```ruby # @rbs *: untyped # @rbs **: String # @rbs &: ? (String) -> bool def foo(*, **) = nil ``` ```ruby def to_s #: String end ``` ```ruby # @rbs yields: String # @rbs skip: untyped # @rbs !return: bool def foo(return:, yields:, skip:) #: void end ``` -------------------------------- ### Inline Constant Type Annotations in Ruby Source: https://context7.com/soutaro/rbs-inline/llms.txt This Ruby code snippet demonstrates how to annotate constants with types using RBS::Inline. It shows annotations placed after the constant definition, before the constant definition, and for array and hash constants with specified element and key/value types. ```ruby # rbs_inline: enabled class Config # Type annotation after constant MAX_SIZE = 100 #: Integer # Type annotation before constant # @rbs VERSION: String VERSION = "1.0.0" # Array constant with element type COLORS = ["red", "green", "blue"] #: Array[String] # Hash constant with key/value types DEFAULTS = { timeout: 30 } #: Hash[Symbol, Integer] end ``` -------------------------------- ### Define Method Types with '#:' Syntax Source: https://github.com/soutaro/rbs-inline/wiki/Syntax-guide The '#:' syntax allows embedding RBS method types directly within Ruby code. Multiple '#:' lines define method overloads. ```ruby #: () -> String def to_s end #: (?Regexp?) -> Enumerator[String, void] #: (?Regexp?) { (String) -> void } -> void def each_person(pattern = nil, &block) end ``` -------------------------------- ### Enable RBS Generation with Magic Comment Source: https://github.com/soutaro/rbs-inline/wiki/Syntax-guide To enable RBS generation for a Ruby file, a '# rbs_inline: enabled' magic comment must be present at the beginning of the file. This comment activates the RBS generation process for the subsequent code. ```ruby # rbs_inline: enabled class Foo end ``` -------------------------------- ### Inline Class and Module Declarations in Ruby Source: https://context7.com/soutaro/rbs-inline/llms.txt This Ruby code showcases inline annotations for class and module declarations using RBS::Inline. It includes generic classes with type parameters, modules with self-type constraints, inheriting classes with type arguments, and block-based module declarations for Structs. ```ruby # rbs_inline: enabled # Generic class with type parameters # @rbs generic T class Container # @rbs @items: Array[T] attr_reader :items #: Array[T] # @rbs items: Array[T] def initialize(items) #: void @items = items end end # Module with self-type constraint # @rbs module-self Enumerable[String] module StringProcessor #: () -> Integer def total_length sum(&:length) end end # Inheriting with type arguments class StringContainer < Container #[String] #: (String) -> void def add(item) items << item end end # Block-based module declaration Struct.new(:x, :y) do # @rbs module Point #: () -> Float def distance Math.sqrt(x**2 + y**2) end end ``` -------------------------------- ### Use Directives and Annotations in Ruby Source: https://context7.com/soutaro/rbs-inline/llms.txt Illustrates the use of `@rbs use` directives to import types from other RBS files or modules and annotations like `%a{pure}` to add metadata to methods. This helps in organizing type definitions and adding custom attributes. ```ruby # rbs_inline: enabled # @rbs use RBS::AST::* # @rbs use ActiveSupport::Concern class TypeHelper # @rbs %a{pure} # @rbs %a{incompatible} #: (String) -> Integer def parse(value) value.to_i end end ``` -------------------------------- ### Release a new version of rbs-inline gem Source: https://github.com/soutaro/rbs-inline/blob/main/README.md This command sequence is used to release a new version of the `rbs-inline` gem. It involves updating the version number, creating a git tag, and pushing the tag and gem to rubygems.org. ```shell bundle exec rake release ``` -------------------------------- ### Define Classes/Modules within Blocks Source: https://github.com/soutaro/rbs-inline/wiki/Syntax-guide For method calls with blocks that implicitly define modules or classes, '@rbs class' and '@rbs module' syntax is introduced. These annotations accept RBS syntax for opening modules/classes. ```ruby module Foo extend ActiveSupport::Concern # @rbs module ClassMethods class_methods do # @rbs () -> Integer def foo = 123 end end ``` -------------------------------- ### Equivalent RBS type definition generated from inline Ruby code Source: https://github.com/soutaro/rbs-inline/blob/main/README.md This is the equivalent RBS (Ruby System) type definition that would be generated from the previously shown Ruby code with embedded inline RBS comments. It presents a clean, standard RBS format for the `Person` class, detailing attribute types and method signatures, including parameter types and return types. ```rbs class Person attr_reader name: String attr_reader addresses: Array[String] def initialize: (name: String, addresses: Array[String]) -> void def to_s: () -> String def each_address: () { (String) -> void } -> void end ``` -------------------------------- ### Define Classes in RBS Source: https://github.com/soutaro/rbs-inline/wiki/Syntax-guide Ruby's 'class' syntax is translated to RBS class definitions. Class and superclass names must follow Ruby's constant syntax. Generic classes can be defined using '# @rbs generic' annotations. ```ruby class Foo end ``` ```ruby # @rbs generic A -- Type of `a` # @rbs generic unchecked in B < String -- Type of `b` class Foo end ``` ```ruby class Foo[A, unchecked in B < String] end ``` ```ruby class Foo < String end class Bar < Array #[String] end ``` ```ruby # @rbs inherits Hash[String, Integer] class Foo < Hash end # @rbs inherits Struct[String | Integer] class Bar < Struct.new(:size, :name, keyword_init: true) end ``` -------------------------------- ### Inline Attribute Type Annotations in Ruby Source: https://context7.com/soutaro/rbs-inline/llms.txt This Ruby code snippet illustrates how to annotate attribute types using RBS::Inline. It shows inline annotations for `attr_reader`, annotations on the following line, multiple attributes with annotations, and type annotations for `attr_accessor` and `attr_writer`. ```ruby # rbs_inline: enabled class Person # Inline type annotation attr_reader :name #: String # Type annotation on following line attr_reader :age #[Integer] # Multiple attributes with type annotation # @rbs @email: String attr_reader :email attr_accessor :score #: Integer private attr_writer :secret #: String end ``` -------------------------------- ### Define Modules in RBS Source: https://github.com/soutaro/rbs-inline/wiki/Syntax-guide The 'module' syntax in Ruby is translated to RBS module definitions. Module names must be constants. Generics are supported via '# @rbs generic', and module self-type constraints use '# @rbs module-self'. ```ruby module Foo end ``` ```ruby # @rbs module-self BasicObject module Kernel end ``` -------------------------------- ### Define Data Class and Generate RBS Source: https://github.com/soutaro/rbs-inline/wiki/Data-Struct-support This snippet demonstrates how to define a 'Data' class with attributes and its corresponding RBS type definition generated by RBS::Inline. It shows the Ruby code for defining the 'Account' class and the resulting RBS output. ```ruby Account = Data.define( :id, #: Integer :email #: String ) Group = Struct.new( :accounts #: Array[Account] ) ``` ```rbs class Account < Data attr_reader id(): Integer attr_reader email(): String def initialize: (Integer id, String email) -> void | (id: Integer, email: String) -> void end class Group < Strcut[untyped] attr_accessor accounts(): Array[Account] def initialize: (?Array[Account] accounts) -> void | (?accounts: Array[Account]) -> void end ``` -------------------------------- ### Embedded RBS Declarations in Ruby Source: https://context7.com/soutaro/rbs-inline/llms.txt Shows how to embed full RBS type declarations directly within Ruby source files using the `# @rbs!` directive. This allows for defining complex types, interfaces, and custom type aliases alongside the Ruby code. ```ruby # rbs_inline: enabled class Database # @rbs! # type connection = { host: String, port: Integer } # # interface _Queryable # def query: (String) -> Array[Hash[Symbol, untyped]] # end # @rbs config: connection def initialize(config) #: void @config = config end end ``` -------------------------------- ### Define Method Types with '# @rbs' Syntax Source: https://github.com/soutaro/rbs-inline/wiki/Syntax-guide The '# @rbs' syntax provides an alternative for specifying method types. Method overloads can be written using '|' separators. This syntax is more verbose but can be clearer for complex types. ```ruby # @rbs () -> String def to_s end # @rbs (?Regexp?) -> Enumerator[String, void] # | (?Regexp?) { (String) -> void } -> void def each_person(pattern = nil, &block) end ``` -------------------------------- ### Annotation Parsing from Ruby Comments (Ruby) Source: https://context7.com/soutaro/rbs-inline/llms.txt This Ruby code uses `rbs-inline` and `prism` to parse comments within Ruby code and extract annotations like variable types and return types. It iterates through parsed results and individual annotations to access their details. ```ruby require "rbs/inline" require "prism" # Parse comments and extract annotations result = Prism.parse(<<~RUBY) # @rbs x: Integer # @rbs return: String def format(x) x.to_s end RUBY # Parse annotations from comments annotations = RBS::Inline::AnnotationParser.parse(result.comments) annotations.each do |parsing_result| # Get line range for the comment block line_range = parsing_result.line_range puts "Lines #{line_range.begin}-#{line_range.end}" # Iterate through annotations parsing_result.each_annotation do |annotation| case annotation when RBS::Inline::AST::Annotations::VarType puts "Variable: #{annotation.name}, Type: #{annotation.type}" when RBS::Inline::AST::Annotations::ReturnType puts "Return type: #{annotation.type}" when RBS::Inline::AST::Annotations::Method annotation.each_method_type do |method_type| puts "Method type: #{method_type}" end end end end ``` -------------------------------- ### Ruby code with embedded RBS type declarations Source: https://github.com/soutaro/rbs-inline/blob/main/README.md This Ruby code snippet demonstrates how to embed RBS type declarations directly within comments using the `# rbs_inline:` and `@rbs` directives. It shows type annotations for class attributes, method parameters, and return types, as well as a shorter `:` syntax for method types. This approach allows for type checking within the Ruby source file itself. ```ruby # rbs_inline: enabled class Person attr_reader :name #: String attr_reader :addresses #: Array[String] # You can write the type of parameters and return types. # # @rbs name: String # @rbs addresses: Array[String] # @rbs return: void def initialize(name:, addresses:) @name = name @addresses = addresses end # Or write the type of the method just after `@rbs` keyword. # # @rbs () -> String def to_s "Person(name = #{name}, addresses = #{addresses.join(', ')})" end # The `:` syntax is the shortest one. # #: () -> String def hash [name, addresses].hash end # @rbs &block: (String) -> void def each_address(&block) #: void addresses.each(&block) end end ``` -------------------------------- ### Alias Declaration Generation in Ruby Source: https://github.com/soutaro/rbs-inline/wiki/Syntax-guide Detects the `alias` syntax in Ruby code and automatically generates corresponding `alias` declarations in RBS. ```ruby class Foo def ==(other) #: bool end alias eql? == end ``` -------------------------------- ### Embedding Direct RBS Elements in Ruby Source: https://github.com/soutaro/rbs-inline/wiki/Syntax-guide The `# @rbs!` annotation allows embedding raw RBS definitions directly within the Ruby code for elements not covered by other annotations. ```ruby class Person include ActiveModel::Model include ActiveModel::Attributes attribute :id, :integer, default: 0 attribute :name, :string, default: '' # @rbs! # attr_accessor id (): Integer # # attr_accessor name (): String end ``` -------------------------------- ### Add rbs-inline gem to Gemfile Source: https://github.com/soutaro/rbs-inline/blob/main/README.md This code snippet shows how to add the `rbs-inline` gem to a Ruby project's `Gemfile`. The `require: false` option is emphasized to prevent type definition dependencies during runtime, as the gem is primarily used for development-time type checking and code generation. ```ruby gem 'rbs-inline', require: false ``` -------------------------------- ### Constant Type Declaration in Ruby Source: https://github.com/soutaro/rbs-inline/wiki/Syntax-guide Declares constants with specific types using the `#:` syntax. The gem can infer simple types for literal values. ```ruby VERSION = "1.2.3" Foo = [1,2,3].sample #: Integer ``` -------------------------------- ### Adding Custom Methods to Data/Struct Classes Source: https://github.com/soutaro/rbs-inline/wiki/Data-Struct-support This snippet shows how to add custom methods to classes defined using `Data.define` or `Struct.new` after their initial assignment. It highlights that RBS::Inline does not directly support adding methods within the definition block but allows for separate class definitions to add methods and their associated RBS annotations. ```ruby Account = Data.define( :id, #: Integer :email #: String ) class Account # @rbs (String) -> void def send_email(body) # Do something end end ``` -------------------------------- ### Attribute Definition with RBS in Ruby Source: https://github.com/soutaro/rbs-inline/wiki/Syntax-guide Supports standard Ruby attribute definition methods like `attr_reader`, `attr_writer`, and `attr_accessor`. RBS annotations can specify the type for these attributes. ```ruby class Foo attr_reader :name #: String attr_reader :size, :count #: Integer end ``` -------------------------------- ### Instance Variable Type Annotation in Ruby Source: https://github.com/soutaro/rbs-inline/wiki/Syntax-guide You can annotate instance variables using `# @rbs @var: Type`. This allows specifying the type for instance variables, including those on the class itself using `self.@var: Type`. ```ruby class Foo # @rbs @name: String -- Instance variable # @rbs self.@all_names: Array[String] -- Instance variable of the class end ``` -------------------------------- ### Skipping RBS Generation in Ruby Source: https://github.com/soutaro/rbs-inline/wiki/Syntax-guide The `# @rbs skip` annotation can be used to prevent the generation of RBS definitions for specific classes, methods, or modules. ```ruby # @rbs skip class HiddenClass end class Foo # @rbs skip def hidden_method end end ``` -------------------------------- ### Override Method Annotation in Ruby Source: https://github.com/soutaro/rbs-inline/wiki/Syntax-guide The `@rbs override` annotation is used to indicate that a method overrides a superclass method. This helps in generating accurate RBS definitions without manually copying super method signatures. ```ruby # @rbs override def foo(x, y) end ``` -------------------------------- ### Annotate Overriding Methods Source: https://github.com/soutaro/rbs-inline/wiki/Syntax-guide The '# @rbs override' annotation is used to indicate that a method is overriding a method from a superclass. This helps in ensuring correct method signatures and behavior. ```ruby # @rbs override def some_method end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.