Skip to content

Introduce RuboCop Performance #316

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Aug 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion .rubocop.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
plugins:
- rubocop-performance
- rubocop-rake
- rubocop-rspec

Expand All @@ -21,7 +22,18 @@ Metrics/MethodLength:
Enabled: false
Metrics/ModuleLength:
Enabled: false
Performance/CollectionLiteralInLoop:
Exclude:
- spec/**/*
Performance/RedundantBlockCall:
Enabled: false # TODO: temporarily disabled to avoid potential breaking change
Performance/StringInclude:
Exclude:
- lib/ruby_llm/providers/**/capabilities.rb
Performance/UnfreezeString:
Exclude:
- spec/**/*
RSpec/ExampleLength:
Enabled: false
RSpec/MultipleExpectations:
Enabled: false
Enabled: false
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ group :development do # rubocop:disable Metrics/BlockLength
gem 'reline'
gem 'rspec', '~> 3.12'
gem 'rubocop', '>= 1.0'
gem 'rubocop-performance'
gem 'rubocop-rake', '>= 0.6'
gem 'rubocop-rspec'
gem 'ruby_llm-schema', '~> 0.1.0'
Expand Down
2 changes: 1 addition & 1 deletion lib/ruby_llm/active_record/acts_as.rb
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ def setup_persistence_callbacks
end

def persist_new_message
@message = messages.create!(role: :assistant, content: String.new)
@message = messages.create!(role: :assistant, content: '')
end

def persist_message_completion(message)
Expand Down
2 changes: 1 addition & 1 deletion lib/ruby_llm/content.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def process_attachments_array_or_string(attachments)
def process_attachments(attachments)
if attachments.is_a?(Hash)
# Ignores types (like :image, :audio, :text, :pdf) since we have robust MIME type detection
attachments.each_value(&method(:process_attachments_array_or_string))
attachments.each_value { |attachment| process_attachments_array_or_string(attachment) }
else
process_attachments_array_or_string attachments
end
Expand Down
2 changes: 1 addition & 1 deletion lib/ruby_llm/models.rb
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def resolve(model_id, provider: nil, assume_exists: false, config: nil) # ruboco

model = Model::Info.new(
id: model_id,
name: model_id.gsub('-', ' ').capitalize,
name: model_id.tr('-', ' ').capitalize,
provider: provider_instance.slug,
capabilities: %w[function_calling streaming],
modalities: { input: %w[text image], output: %w[text] },
Expand Down
2 changes: 1 addition & 1 deletion lib/ruby_llm/providers/bedrock/streaming/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def stream_response(connection, payload, additional_headers = {}, &block)
end

def handle_stream(&block)
buffer = String.new
buffer = +''
proc do |chunk, _bytes, env|
if env && env.status != 200
handle_failed_response(chunk, buffer, env)
Expand Down
4 changes: 2 additions & 2 deletions lib/ruby_llm/providers/openai/capabilities.rb
Original file line number Diff line number Diff line change
Expand Up @@ -198,11 +198,11 @@ def apply_special_formatting(name)
.gsub(/(\d{4}) (\d{2}) (\d{2})/, '\1\2\3')
.gsub(/^(?:Gpt|Chatgpt|Tts|Dall E) /) { |m| special_prefix_format(m.strip) }
.gsub(/^O([13]) /, 'O\1-')
.gsub(/^O[13] Mini/, '\0'.gsub(' ', '-'))
.gsub(/^O[13] Mini/, '\0'.tr(' ', '-'))
.gsub(/\d\.\d /, '\0'.sub(' ', '-'))
.gsub(/4o (?=Mini|Preview|Turbo|Audio|Realtime|Transcribe|Tts)/, '4o-')
.gsub(/\bHd\b/, 'HD')
.gsub(/(?:Omni|Text) Moderation/, '\0'.gsub(' ', '-'))
.gsub(/(?:Omni|Text) Moderation/, '\0'.tr(' ', '-'))
.gsub('Text Embedding', 'text-embedding-')
end

Expand Down
4 changes: 2 additions & 2 deletions lib/ruby_llm/stream_accumulator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class StreamAccumulator
attr_reader :content, :model_id, :tool_calls

def initialize
@content = String.new
@content = +''
@tool_calls = {}
@input_tokens = 0
@output_tokens = 0
Expand Down Expand Up @@ -66,7 +66,7 @@ def accumulate_tool_calls(new_tool_calls)
new_tool_calls.each_value do |tool_call|
if tool_call.id
tool_call_id = tool_call.id.empty? ? SecureRandom.uuid : tool_call.id
tool_call_arguments = tool_call.arguments.empty? ? String.new : tool_call.arguments
tool_call_arguments = tool_call.arguments.empty? ? +'' : tool_call.arguments
@tool_calls[tool_call.id] = ToolCall.new(
id: tool_call_id,
name: tool_call.name,
Expand Down
2 changes: 1 addition & 1 deletion lib/ruby_llm/streaming.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def handle_stream(&block)
private

def to_json_stream(&)
buffer = String.new
buffer = +''
parser = EventStreamParser::Parser.new

create_stream_processor(parser, buffer, &)
Expand Down
4 changes: 2 additions & 2 deletions lib/tasks/aliases.rake
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ namespace :aliases do # rubocop:disable Metrics/BlockLength

base_name = Regexp.last_match(1)
# Normalize to Anthropic naming convention
anthropic_name = base_name.gsub('.', '-')
anthropic_name = base_name.tr('.', '-')

# Skip if we already have an alias for this
next if aliases[anthropic_name]
Expand All @@ -91,7 +91,7 @@ namespace :aliases do # rubocop:disable Metrics/BlockLength
# OpenRouter uses "google/" prefix and sometimes different naming
openrouter_variants = [
"google/#{model}",
"google/#{model.gsub('gemini-', 'gemini-').gsub('.', '-')}",
"google/#{model.gsub('gemini-', 'gemini-').tr('.', '-')}",
"google/#{model.gsub('gemini-', 'gemini-')}"
]

Expand Down
8 changes: 4 additions & 4 deletions lib/tasks/models_docs.rake
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def generate_models_markdown
end

def generate_provider_sections
RubyLLM::Provider.providers.map do |provider, provider_class|
RubyLLM::Provider.providers.filter_map do |provider, provider_class|
models = RubyLLM.models.by_provider(provider)
next if models.none?

Expand All @@ -95,7 +95,7 @@ def generate_provider_sections

#{models_table(models)}
PROVIDER
end.compact.join("\n\n")
end.join("\n\n")
end

def generate_capability_sections
Expand All @@ -107,15 +107,15 @@ def generate_capability_sections
'Batch Processing' => RubyLLM.models.select { |m| m.capabilities.include?('batch') }
}

capabilities.map do |capability, models|
capabilities.filter_map do |capability, models|
next if models.none?

<<~CAPABILITY
### #{capability} (#{models.count})

#{models_table(models)}
CAPABILITY
end.compact.join("\n\n")
end.join("\n\n")
end

def generate_modality_sections # rubocop:disable Metrics/PerceivedComplexity
Expand Down
2 changes: 1 addition & 1 deletion spec/ruby_llm/chat_error_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

RSpec::Matchers.define :look_like_json do
match do |actual|
actual.strip.start_with?('{') || actual.strip.start_with?('[')
actual.strip.start_with?('{', '[')
end

failure_message do |actual|
Expand Down
2 changes: 1 addition & 1 deletion spec/ruby_llm/chat_tools_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ def execute(query:)
# Monkey-patch to count complete calls
described_class.define_method(:complete) do |&block|
call_count += 1
original_complete.bind(self).call(&block)
original_complete.bind_call(self, &block)
end

chat = RubyLLM.chat.with_tool(HaltingTool)
Expand Down