### Install Solargraph Gem Source: https://solargraph.org/guides/getting-started Installs the Solargraph gem via the command line. ```bash gem install solargraph ``` -------------------------------- ### Install Xcode Command Line Tools Source: https://solargraph.org/guides/troubleshooting Ensure the necessary development tools are installed to build native extensions on macOS. ```bash xcode-select --install sudo xcodebuild -license ``` -------------------------------- ### Get Completion Suggestions Source: https://solargraph.org/guides/code-examples Retrieve code completion suggestions for a given position in a source file. Requires mapping the source to an ApiMap and using clip_at to get the relevant context. ```ruby api_map = Solargraph::ApiMap.new source = Solargraph::Source.load_string("String.", 'example.rb') api_map.map source clip = api_map.clip_at('example.rb', Solargraph::Position.new(0, 7)) completion = clip.complete # Suggestions will include String class methods ``` -------------------------------- ### Install macOS Ruby Headers Source: https://solargraph.org/guides/troubleshooting Manually install Ruby headers required for native extensions on macOS 10.14. ```bash open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg ``` -------------------------------- ### Query Ruby Core Methods with ApiMap Source: https://solargraph.org/guides/code-examples Get public instance methods of a Ruby class, such as String. Requires initializing an ApiMap. ```ruby api_map = Solargraph::ApiMap.new pins = api_map.get_methods('String') # Get public instance methods of the # String class ``` -------------------------------- ### Method Call Arity Check Example Source: https://solargraph.org/guides/type-checking This example demonstrates Solargraph's method call arity check, ensuring that the number of arguments passed to a method matches its defined parameters. An error is reported for too many arguments. ```ruby # Arity check example def example(arg1, arg2 = 0); end example(1) # OK example(1, 2) # OK example(1, 2, 3) # Error: Too many arguments ``` -------------------------------- ### Solargraph Scan Output Example Source: https://solargraph.org/guides/scanning-workspaces The verbose output of `solargraph scan -v` lists each code pin analyzed, along with its mapping. A successful scan concludes with a summary of scanned files and pins, and the time taken. ```text | Solargraph Solargraph::ApiMap Solargraph::ApiMap::Cache Solargraph::ApiMap::Cache.new Solargraph::ApiMap::Cache#initialize Solargraph::ApiMap::Cache#initialize | @methods Solargraph::ApiMap::Cache#initialize | @constants # (several thousand lines truncated) Scanned /solargraph (44246 pins) in 35.820807722979225 seconds. ``` -------------------------------- ### Overloaded Methods: Tag Inheritance Source: https://solargraph.org/guides/type-checking Overloaded methods inherit type tags from superclasses or included modules. This example shows a correct inheritance and an error where the declared return type mismatches the inherited type. ```ruby module Mixin # @return [Integer] def integer 100 end end class User1 include Mixin # OK: User1#integer returns same type as Mixin#integer # def integer 200 end end class User2 include Mixin # Error: Declared return type Integer does not match inferred type String # def integer '100' end end ``` -------------------------------- ### Strict Level: Parameter Validation Source: https://solargraph.org/guides/type-checking If a method includes `@param` tags, the type checker validates the arguments passed during method calls. This example shows a correct call and an incorrect one. ```ruby class StrictExample # @param arg1 [Integer] # @return [String] def method1(arg1) arg1.to_s end end # OK: Method call has valid argument StrictExample.new.method1(100) # Error: arg1 expected Integer, received String StrictExample.new.method1('100') ``` -------------------------------- ### Undefined Types Handling Source: https://solargraph.org/guides/type-checking At strict and strong levels, calls to undefined return types result in an 'unresolved call' error, unlike normal checks which ignore them. This example illustrates the error when calling a non-existent method on an inferred nil type. ```ruby class Example def method1; end end Example.new.method1.method2 # Normal type checks ignore the call to `method2` because the return type of # `Example#method1` is untagged. # # Strict type checks report an error because `Example#method1` is inferred to # be `nil` and `NilClass#method2` is not a recognized method. ``` -------------------------------- ### Download Core Documentation Source: https://solargraph.org/guides/getting-started Downloads documentation for the current Ruby version to enable language server features. ```bash solargraph download-core ``` -------------------------------- ### Verify Ruby and Solargraph Versions Source: https://solargraph.org/guides/troubleshooting Check the environment configuration from the command line to ensure the correct versions are being used. ```bash $ cd /path/to/workspace $ ruby -v $ solargraph -v ``` -------------------------------- ### Run Solargraph Typechecker from Command Line Source: https://solargraph.org/guides/type-checking Execute the Solargraph typechecker from your workspace's root directory. Use this to check all files in the project. ```bash solargraph typecheck ``` -------------------------------- ### Switch Xcode Command Line Tools Path Source: https://solargraph.org/guides/troubleshooting Configure the path for Xcode command line tools if native extension builds fail on Xcode 11. ```bash sudo xcode-select --switch /Library/Developer/CommandLineTools sudo xcode-select --switch /Applications/Xcode.app ``` -------------------------------- ### Query Definitions from Source Location Source: https://solargraph.org/guides/code-examples Find definitions of variables or methods at a specific location within a source file after virtualizing it. Requires an ApiMap and a Solargraph::Source object. ```ruby api_map = Solargraph::ApiMap.new source = Solargraph::Source.load_string("x = 'string'; puts x", 'example.rb') api_map.virtualize source clip = api_map.clip_at('example.rb', Solargraph::Position.new(0, 23)) pins = clip.define # `var` is recognized as a local variable of type String ``` -------------------------------- ### Custom Solargraph Methods Source: https://solargraph.org/guides/language-server Documentation for custom LSP methods implemented by Solargraph for documentation retrieval and server maintenance. ```APIDOC ## $/solargraph/search ### Description Search the documentation for class names, methods, etc. ## $/solargraph/document ### Description Get a page of generated documentation for a class, module, or method. ## $/solargraph/documentGems ### Description Build YARD documentation for installed gems. ## $/solargraph/downloadCore ### Description Download the most up-to-date version of the Ruby core documentation. ## $/solargraph/environment ### Description Get information about the current environment (gem version, config settings, etc.). ## $/solargraph/checkGemVersion ### Description Check if a newer version of the gem is available. ## $/solargraph/restartServer ### Description A notification sent from the server to the client requesting that the client shut down and restart the server. ``` -------------------------------- ### Custom Solargraph Include Configuration Source: https://solargraph.org/guides/performance Customize the .solargraph.yml file to include only specific directories, such as 'lib' and 'app', for faster workspace mapping. ```yaml include: - "lib/**/*.rb" - "app/**/*.rb" ``` -------------------------------- ### Documenting return types with @return Source: https://solargraph.org/guides/yard Use @return to specify the return type of a method or attribute. ```ruby class Example # @return [String] def stringify 'example' end end Example.new.stringify # <= Recognized as a String ``` ```ruby class Example # @return [Integer] attr_reader :number end ``` -------------------------------- ### Load Workspace into ApiMap Source: https://solargraph.org/guides/code-examples Load an entire Ruby workspace into an ApiMap for comprehensive analysis. This includes constants defined in the project's code. ```ruby api_map = Solargraph::ApiMap.load('/path/to/workspace') pins = api_map.get_constants('') # Results will include constants defined in # the project's code ``` -------------------------------- ### Configure Required Paths Source: https://solargraph.org/guides/configuration Add require paths that are not explicitly defined in the project code. ```yaml require: - sinatra/base ``` -------------------------------- ### Configure Solargraph Plugin in .solargraph.yml Source: https://solargraph.org/guides/plugins Registers the plugin gem and enables the custom reporter within the project configuration. ```yaml plugins: - solargraph-frozen-string reporters: - frozen-string ``` -------------------------------- ### Defining method overloads with @overload Source: https://solargraph.org/guides/yard Use @overload to document multiple parameter signatures and their corresponding return types. ```ruby class Example # Return one object according to its name or an array of objects from an # array of names. # # @overload find(name) # @param name [String] # @return [Object] # @overload find(list) # @param list [Array] # @return [Array] def find(*args); end end example = Example.new example.find('Bob') # => Object example.find(['Bob', 'Jane']) # => Array ``` -------------------------------- ### Default Solargraph Configuration Source: https://solargraph.org/guides/configuration The default structure of the .solargraph.yml configuration file. ```yaml include: - "**/*.rb" exclude: - spec/**/* - test/**/* - vendor/**/* - ".bundle/**/*" require: [] domains: [] reporters: - rubocop - require_not_found max_files: 5000 ``` -------------------------------- ### Default Solargraph Include Configuration Source: https://solargraph.org/guides/performance This is the default configuration for the .solargraph.yml file, which includes all Ruby files in the workspace. ```yaml include: - "**/*.rb" ``` -------------------------------- ### Configure Diagnostic Reporters Source: https://solargraph.org/guides/configuration Specify which diagnostic reporters the language server should use. ```yaml reporters: - rubocop - require_not_found ``` -------------------------------- ### Documenting parameters with @param Source: https://solargraph.org/guides/yard Use @param to define the expected type of a method argument for type checking. ```ruby class Example # @param int [Integer] def take_a_number(int) int # <= Recognized as an Integer end end Example.new.take_a_number(100) # Passes strict type checks Example.new.take_a_number('A') # Fails strict type checks ``` -------------------------------- ### Run Solargraph Typechecker on a Specific File Source: https://solargraph.org/guides/type-checking Check for type problems in a particular Ruby file by providing its path to the Solargraph typechecker command. ```bash solargraph ./path/to/file.rb ``` -------------------------------- ### Documenting yielded parameters with @yieldparam Source: https://solargraph.org/guides/yard Use @yieldparam to specify the types of parameters passed into a block. ```ruby class Example # @yieldparam [String] def change yield 'example' end end Example.new.change do |str| str # <= Recognized as a String end ``` -------------------------------- ### Defining methods with @!method Source: https://solargraph.org/guides/yard Use the @!method directive to manually add methods to the Solargraph code map. ```ruby class Example # @return [String] def foo; end # @!method bar() # @return [String] end Example.new. # `foo` and `bar` are recognized as available methods ``` -------------------------------- ### Register Custom Language Server Message Source: https://solargraph.org/guides/code-examples Extend the Solargraph language server by registering a custom message handler. The handler must inherit from Solargraph::LanguageServer::Message::Base and implement a `process` method. ```ruby class MyMessage < Solargraph::LanguageServer::Message::Base def process STDERR.puts "Server received MyMessage parameters: #{params}" end end Solargraph::LanguageServer::Message.register '$/myMessage', MyMessage ``` -------------------------------- ### Add File Source to ApiMap Source: https://solargraph.org/guides/code-examples Add a Ruby source file to an ApiMap for analysis. This allows querying constants defined within the added source. ```ruby api_map = Solargraph::ApiMap.new source = Solargraph::Source.load_string('class MyClass; end', 'my_class.rb') api_map.map source # Add the source to the map pins = api_map.get_constants('') # The constants in the global namespace will # include `MyClass` ``` -------------------------------- ### Scan Workspace with Solargraph Source: https://solargraph.org/guides/scanning-workspaces Navigate to your workspace and run the `solargraph scan -v` command to perform a verbose scan. This command checks for code that Solargraph cannot parse or map, outputting details for each analyzed code pin. ```bash cd /path/to/workspace solargraph scan -v ``` -------------------------------- ### Overriding documentation with @!override Source: https://solargraph.org/guides/yard Use @!override to add or modify documentation for methods defined in external libraries. ```ruby # Specify the return type of the Ruby stdlib's Benchmark.measure method # @!override Benchmark.measure # @return [Benchmark::Tms] result = Benchmark.measure { puts 'test' } result # => Benchmark::Tms ``` -------------------------------- ### Parsing code with @!parse Source: https://solargraph.org/guides/yard Use @!parse to force Solargraph to map arbitrary code blocks as if they were part of the runtime. ```ruby module ClassMethods def other_method; end end class Example # @!parse # extend ClassMethods end Example. # `other_method` is recognized as an available method ``` -------------------------------- ### Configure Solargraph Typecheck Reporter Source: https://solargraph.org/guides/type-checking Add 'typecheck' to your workspace's reporters in `.solargraph.yml` to enable editor diagnostics. You can also specify a check level like 'strict'. ```yaml reporters: - typecheck ``` ```yaml reporters: - typecheck:strict ``` -------------------------------- ### Implement a Frozen String Literal Diagnostics Reporter Source: https://solargraph.org/guides/plugins Defines a custom diagnostic reporter that warns if a file lacks the frozen_string_literal comment. Requires the solargraph gem. ```ruby # solargraph-frozen-string.rb require 'solargraph' class FrozenStringReporter < Solargraph::Diagnostics::Base def diagnose source, _api_map return [] if source.code.empty? || source.code.start_with?('# frozen_string_literal:') [ { range: Solargraph::Range.from_to(0, 0, 0, source.code.lines[0].length).to_hash, severity: Solargraph::Diagnostics::Severities::WARNING, source: 'FrozenString', message: 'File does not start with frozen_string_literal.' } ] end end Solargraph::Diagnostics.register 'frozen-string', FrozenStringReporter ``` -------------------------------- ### Strong Level: Parameter and Return Type Requirements Source: https://solargraph.org/guides/type-checking Strong checks mandate that all method parameters and return types must be explicitly tagged. Inferred types must also match these tags. Untagged parameters will cause an error. ```ruby class StrongExample # OK: Parameter and return types are valid. # # @param arg1 [Integer] # @return [String] def method1(arg1) arg1.to_s end # Error: Parameter type is untagged. # # @return [String] def method2(arg1) "received #{arg1}" end end # OK: Method call is correct StrongExample.new.method1(100) # Error: arg1 expected Integer, received String StrongExample.new.method1('100') ``` -------------------------------- ### Strict Level: Attribute Type Tagging Source: https://solargraph.org/guides/type-checking Attributes require `@return` tags because their types cannot be inferred from code. Untagged attributes will result in an error. ```ruby class StrictExample # OK: Attribute has a `@return` tag # # @return [String] attr_reader :attr1 # Error: Untagged attribute cannot be inferred # attr_reader :attr2 end ``` -------------------------------- ### Register Custom Diagnostics Reporter Source: https://solargraph.org/guides/code-examples Add a custom diagnostics reporter to Solargraph. The reporter must inherit from Solargraph::Diagnostics::Base and implement a `diagnose` method that returns LSP-compliant diagnostic objects. ```ruby class MyReporter < Solargraph::Diagnostics::Base def diagnose source, api_map # Return an array of hash objects that conform to the LSP's Diagnostic # specification [] end end Solargraph::Diagnostics.register 'my_reporter', MyReporter ``` -------------------------------- ### Infer Type from Static Analysis Source: https://solargraph.org/guides/type-detection When no type tags are present, Solargraph attempts to infer types by analyzing the code's static structure. This is demonstrated by inferring the return type of `my_string`. ```ruby class MyClass def my_string 'my_string' end end MyClass.new.my_string # <= Inferred to be a String ``` -------------------------------- ### Defining attributes with @!attribute Source: https://solargraph.org/guides/yard Use the @!attribute directive to manually add attributes to the Solargraph code map. ```ruby class Example # @return [String] attr_accessor :foo # @!attribute [rw] bar # @return [String] end Example.new. # `foo` and `bar` are recognized as available attributes ``` -------------------------------- ### Define Abstract Methods with NotImplementedError Source: https://solargraph.org/guides/type-checking A base class defines an interface method that raises NotImplementedError, which subclasses are expected to override. ```ruby class Greeter # Subclasses should implement this method # # @return [String] def greeting raise NotImplementedError end # @return [void] def say_greeting puts greeting end end class Person < Greeter def greeting "Hello!" end end class Cowboy < Greeter def greeting "Howdy!" end end class Stranger < Greeter end Person.new.say_greeting #=> "Hello!" Cowboy.new.say_greeting #=> "Howdy!" Stranger.new.say_greeting #=> NotImplementedError ``` -------------------------------- ### Define Return Type with @return Tag Source: https://solargraph.org/guides/type-detection Use the `@return` YARD tag to specify the return type of a method or attribute. This is useful for explicit type definition. ```ruby class MyClass # @return [String] attr_accessor :my_string # @return [Integer] def my_integer end end ``` -------------------------------- ### Ignore Typechecker Errors with @sg-ignore Source: https://solargraph.org/guides/type-checking Use the `@sg-ignore` directive to tell the typechecker to ignore specific errors, such as unrecognized constants or type inference discrepancies in method tags. ```ruby # @sg-ignore UnknownConstant1 # not reported UnknownConstant2 # reported ``` ```ruby # Ignore the discrepancy between tagged type `String` and inferred type `Integer` # @sg-ignore # @return [String] def foo 100 end ``` -------------------------------- ### Setting block context with @yieldreceiver Source: https://solargraph.org/guides/yard Use @yieldreceiver to indicate that the block's self context should be treated as a specific type. ```ruby module Example # @yieldreceiver [String] def self.inside_string; end end Example.inside_string do # Solargraph knows that this block's `self` is a String, so String instance # methods like `upcase` are available here. end ``` -------------------------------- ### Use @abstract Tag for Type Checking Source: https://solargraph.org/guides/type-checking The @abstract tag informs Solargraph that the return type defined in the base class should be enforced on subclasses. ```ruby class Greeter # @abstract # @return [String] def greeting raise NotImplementedError end end class Right < Greeter # OK: The implementation satisfies the abstract method's expectations # def greeting "hello" end end class Wrong < Greeter # Error: Declared return type String does not match inferred type Integer # def greeting 100 end end ``` -------------------------------- ### Define Parameter Type with @param Tag Source: https://solargraph.org/guides/type-detection Use the `@param` YARD tag to define the type of a method parameter. Ensure the tag matches the parameter name. ```ruby class MyClass # @param num [Integer] def my_method(num) end end ``` -------------------------------- ### Inherit Type from Super Method Source: https://solargraph.org/guides/type-detection Solargraph checks super methods for type tags if a method does not have its own. This allows for type definitions to be inherited. ```ruby module MyModule # @return [String] def my_string end end class MyClass include MyModule def my_string # <= Inherits String return type from MyModule end end ``` -------------------------------- ### Define Variable Type with @type Tag Source: https://solargraph.org/guides/type-detection Use the `@type` YARD tag to specify the type of a variable. This helps Solargraph understand variable types when they are not immediately obvious. ```ruby # @type [String] my_string = get_a_string ``` -------------------------------- ### Strict Level: Method Type Inference Source: https://solargraph.org/guides/type-checking In the strict level, methods must have a tagged type or an inferred type. Untagged methods with uninferrable types will cause a warning. `@param` tags are optional but checked if present. ```ruby class StrictExample # OK: Type checker knows this method returns a String # def method1 'a string' end # OK: Tagged type matches inferred type # # @return [String] def method2 'a string' end # Error: Method's type could not be inferred # def method3 unknown_method end end ``` -------------------------------- ### Solargraph Typed Level Type Checking Source: https://solargraph.org/guides/type-checking The Typed check level compares YARD type tags with inferred types. It validates `@return`, `@type`, and `@param` tags against inferred types and arguments, while still ignoring undefined types. Loose `@return` tag matches are accepted. ```ruby class TypedExample # OK: Return type matches inferred type # # @return [String] def method1 'a string' end # Error: Tagged type Integer does not match inferred type String # # @return [Integer] def method2 'a string' end # OK: Method without `@return` tag is ignored # def method3 'a string' end # OK: Tagged type is valid when inferred type is unknown # # @return [String] def method4 unknown_method end end ``` -------------------------------- ### Specifying variable types with @type Source: https://solargraph.org/guides/yard Use @type to explicitly define the type of a variable for better inference. ```ruby # @type [String] str = method_returning_string str # => String ``` -------------------------------- ### Solargraph Normal Level Type Checking Source: https://solargraph.org/guides/type-checking The Normal check level validates YARD type tags and the arity of calls to explicit methods, but ignores untagged types and undefined types. It resolves namespaces in all type tags. ```ruby class NormalExample # OK: Return type is a recognized class # # @return [String] def method1; end # Error: NotARealClass could not be resolved # # @return [NotARealClass] def method2; end # OK: Method without `@return` tag is ignored def method3; end end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.