Skip to content
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
2 changes: 1 addition & 1 deletion .ruby-version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
4.0.1
4.0.3
4 changes: 2 additions & 2 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ GEM
bindex (0.8.1)
bootsnap (1.23.0)
msgpack (~> 1.2)
brakeman (8.0.4)
brakeman (8.0.6)
racc
builder (3.3.0)
capybara (3.40.0)
Expand Down Expand Up @@ -658,7 +658,7 @@ CHECKSUMS
bigdecimal (4.1.1) sha256=1c09efab961da45203c8316b0cdaec0ff391dfadb952dd459584b63ebf8054ca
bindex (0.8.1) sha256=7b1ecc9dc539ed8bccfc8cb4d2732046227b09d6f37582ff12e50a5047ceb17e
bootsnap (1.23.0) sha256=c1254f458d58558b58be0f8eb8f6eec2821456785b7cdd1e16248e2020d3f214
brakeman (8.0.4) sha256=7bf921fa9638544835df9aa7b3e720a9a72c0267f34f92135955edd80d4dcf6f
brakeman (8.0.6) sha256=759cc69341115e6c2dcd47b6fd8649a0b9bd540e3585ac8a0a94e31c66fee386
builder (3.3.0) sha256=497918d2f9dca528fdca4b88d84e4ef4387256d984b8154e9d5d3fe5a9c8835f
capybara (3.40.0) sha256=42dba720578ea1ca65fd7a41d163dd368502c191804558f6e0f71b391054aeef
concurrent-ruby (1.3.6) sha256=6b56837e1e7e5292f9864f34b69c5a2cbc75c0cf5338f1ce9903d10fa762d5ab
Expand Down
1 change: 1 addition & 0 deletions app/controllers/madmin/settings_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ def update

def setting_params
params.require(:setting).permit(
:carto_api_key,
:github_api_token,
:github_rubycommunity_client_id,
:github_rubycommunity_client_secret,
Expand Down
4 changes: 4 additions & 0 deletions app/helpers/application_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,10 @@ def community_map_data_url
end
end

def carto_basemap_api_key
Setting.get(:carto_api_key).to_s
end

def main_site_url(path)
if Rails.env.production? && request.host == Rails.application.config.x.domains.community
"https://#{Rails.application.config.x.domains.primary}#{path}"
Expand Down
8 changes: 7 additions & 1 deletion app/javascript/controllers/community_map_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export default class extends Controller {
static targets = ["container", "loading"]
static values = {
dataUrl: String,
cartoApiKey: { type: String, default: "" },
fitBounds: { type: Object, default: {} }
}

Expand Down Expand Up @@ -92,6 +93,11 @@ export default class extends Controller {
document.head.appendChild(script)
}

get basemapUrl() {
const base = "https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png"
return this.cartoApiKeyValue ? `${base}?key=${encodeURIComponent(this.cartoApiKeyValue)}` : base
}

initMap() {
this.readyForBoundsUpdate = false

Expand All @@ -108,7 +114,7 @@ export default class extends Controller {
attributionControl: true
})

L.tileLayer("https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png", {
L.tileLayer(this.basemapUrl, {
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="https://carto.com/">CARTO</a>',
subdomains: "abcd",
maxZoom: 20
Expand Down
3 changes: 3 additions & 0 deletions app/jobs/generate_testimonial_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ class GenerateTestimonialJob < ApplicationJob
queue_as :default

def perform(testimonial)
# Translate first so the heading, subheading and body are written from the
# English text rather than from a language the book does not print.
testimonial.translate_to_english! if testimonial.needs_translation?
testimonial.generate_ai_fields!
end
end
2 changes: 1 addition & 1 deletion app/models/concerns/post/ai_summarizable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def generate_summary!(force: false)

chat = user.chats.create!(
purpose: "summary",
model: Model.find_by(model_id: Setting.get(:summary_model, default: Setting::DEFAULT_AI_MODEL))
model: Model.resolve(Setting.get(:summary_model, default: Setting::DEFAULT_AI_MODEL))
)

prompt = "Output ONLY a single teaser sentence. No preamble. Maximum 200 characters. Hook the reader with the most intriguing aspect.\n\nTeaser:\n\n#{text_to_summarize}"
Expand Down
5 changes: 4 additions & 1 deletion app/models/concerns/testimonial/ai_generatable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def generate_ai_fields!

chat = user.chats.create!(
purpose: "testimonial_generation",
model: Model.find_by(model_id: Setting.get(:testimonial_model, default: Setting::DEFAULT_AI_MODEL))
model: Model.resolve(Setting.get(:testimonial_model, default: Setting::DEFAULT_AI_MODEL))
)

parsed = ask_and_parse(chat, system_prompt, user_prompt)
Expand Down Expand Up @@ -102,6 +102,9 @@ def build_generation_prompt(existing_headings)
- USE simple verbs: "is", "has", "does" — not "serves as", "boasts", "features"
- BE specific and concrete. Say what Ruby actually does, not how significant it is.
- Write like a developer talking to a friend, not a press release.
- NEVER name the author or refer to them in the third person. Do not write "Michael's journey",
"developers like Joe", "for Igor" or "Pavlo's favourite framework". The user's name and bio are
context for you only. Write about Ruby, not about the person.

Respond with valid JSON only: {"heading": "...", "subheading": "...", "body_text": "..."}
PROMPT
Expand Down
85 changes: 85 additions & 0 deletions app/models/concerns/testimonial/ai_translatable.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# Quotes arrive in whatever language the author writes in. The book and the site
# are English, so a non-English quote is translated to English before it can be
# published — and the author's own words are kept in quote_original, never lost.
module Testimonial::AiTranslatable
extend ActiveSupport::Concern

ENGLISH = "en".freeze

LANGUAGE_NAMES = {
"english" => "en", "italian" => "it", "spanish" => "es", "portuguese" => "pt",
"french" => "fr", "german" => "de", "russian" => "ru", "ukrainian" => "uk",
"japanese" => "ja", "korean" => "ko", "chinese" => "zh", "turkish" => "tr",
"polish" => "pl", "dutch" => "nl", "indonesian" => "id", "vietnamese" => "vi",
"arabic" => "ar", "hindi" => "hi", "serbian" => "sr", "croatian" => "hr",
"czech" => "cs", "romanian" => "ro", "greek" => "el", "hebrew" => "he",
"swedish" => "sv", "norwegian" => "no", "danish" => "da", "finnish" => "fi"
}.freeze

def translated? = quote_original.present?

def needs_translation? = quote.present? && !translated?

# Detects the language and, when it isn't English, rewrites `quote` in English
# while preserving the original. Returns true when a translation was written.
def translate_to_english!
return false if quote.blank?

chat = user.chats.create!(
purpose: "testimonial_translation",
model: Model.resolve(Setting.get(:translation_model, default: Setting::DEFAULT_AI_MODEL))
)

parsed = JSON.parse(chat.ask(translation_prompt).content.strip.gsub(/\A```(?:json)?\n?/, "").gsub(/\n?```\z/, ""))
language = normalize_language(parsed["language"])
english = parsed["english"].to_s.strip.presence

return false if language.nil? || language == ENGLISH
return false if english.nil? || english == quote

update!(
quote_original: quote,
quote_language: language,
quote: english,
system_generated: true
)
true
rescue JSON::ParserError => e
Rails.logger.error "Failed to parse translation response for testimonial #{id}: #{e.message}"
false
rescue => e
Rails.logger.error "Failed to translate testimonial #{id}: #{e.message}"
false
end

private

# Models answer this with either an ISO code ("it") or a name ("Italian"),
# so accept both and always store the code.
def normalize_language(value)
raw = value.to_s.strip.downcase
return nil if raw.blank?
return LANGUAGE_NAMES[raw] if LANGUAGE_NAMES.key?(raw)
return raw[0, 2] if raw.match?(/\A[a-z]{2}(-[a-z]{2,})?\z/)

raw
end

def translation_prompt
<<~PROMPT
Identify the language of the testimonial below and translate it to English.

Rules:
- "language" is the ISO 639-1 code of the language the testimonial is written in.
- If it is already English, return the code "en" and copy the text unchanged into "english".
- A testimonial that is mostly English but quotes a phrase in another language counts as English.
- Translate the WHOLE text. Never shorten, summarise, omit or truncate any part of it.
- Keep the author's voice, tone and any emoji. Do not add commentary.

Testimonial:
#{quote}

Respond with valid JSON only: {"language": "xx", "english": "..."}
PROMPT
end
end
28 changes: 26 additions & 2 deletions app/models/concerns/testimonial/ai_validatable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def validate_with_ai!

chat = user.chats.create!(
purpose: "testimonial_validation",
model: Model.find_by(model_id: Setting.get(:validation_model, default: Setting::DEFAULT_AI_MODEL))
model: Model.resolve(Setting.get(:validation_model, default: Setting::DEFAULT_AI_MODEL))
)

response = chat.ask("#{system_prompt}\n\n#{user_prompt}")
Expand Down Expand Up @@ -63,7 +63,31 @@ def build_validation_prompt(existing_testimonials)
- Hate speech, slurs, personal attacks, or targeted insults toward individuals or groups are NEVER allowed.
- Casual expletives used positively (e.g., "Damn, Ruby is amazing!" or "Fuck, I love this language!") are ALLOWED.
- The key distinction: profanity expressing enthusiasm = OK. Profanity attacking or demeaning people/groups = NOT OK.
- The quote MUST express genuine love or appreciation for Ruby. This is an advocacy site — negative, dismissive, sarcastic, or trolling sentiments about Ruby are NOT allowed.
- The quote MUST express genuine love or appreciation for Ruby (or Ruby's ecosystem, community, tooling, or the developer experience it enables). This is an advocacy site — negative, dismissive, sarcastic, or trolling sentiments about Ruby are NOT allowed.
- The quote MUST be a first-person testimonial ABOUT Ruby. It is NOT a place for:
* user bios, résumés, or "about me" text (e.g., "Rails developer from South Korea, RFID specialist")
* lists of the user's projects, employers, job titles, contact info, links, or credentials
* generic descriptions of what Ruby is used for, with no personal sentiment attached
* off-topic content (other languages, unrelated announcements, self-promotion)
If the quote reads like a profile blurb, CV bullet, or product pitch rather than "here is why I love Ruby", reject it with reject_reason "quote".
- The quote MUST be primarily about Ruby. Reject if Ruby is a passing mention and the real subject is another language or the author's own project.
- The quote MUST be coherent, readable prose. Reject text that is garbled, unfinished, or impossible to follow.
- The quote MUST NOT sell anything. Reject agency pitches, availability-for-hire notes, growth claims used as marketing ("we ship at 30x speed"), or any call to action.

REJECTION EXAMPLES — these are all reject_reason "quote". Judge new quotes at this standard:
* "800+ apps. All Rails. Ruby's clean syntax makes it the best for AI development. We ship at 30x speed. I help founders and teams build, scale, and ship Rails apps fast. Let's build something. Visit example.com"
→ REJECT: lead-generation advertising with a call to action, not a testimonial.
* "Using Ruby and Rails to help UK heritage get funding. Read my blog here: https://example.com/@me"
→ REJECT: a link dump. States what the author does, never says anything about loving Ruby.
* "Simplicity, elegance and happiness. Like where on earth do you see unless being used."
→ REJECT: incoherent, the second sentence does not parse.
* "It's very convenient for small build scripts. I usually use Rake for tiny tasks. This is because why there is Rakefile in my Rust project."
→ REJECT: broken grammar, and the subject is the author's Rust project rather than a love of Ruby.

ACCEPTANCE EXAMPLES — publish quotes of this kind even when short or plainly worded:
* "I love Ruby because I can build my MVP in a few days." → ACCEPT: brief, but a genuine first-person reason.
* "Ruby was my first love... It's a joy to work with. User-friendly, versatile and productive." → ACCEPT.
* "I came to Ruby from Perl and PHP years ago and still can't leave. I also love Elixir." → ACCEPT: mentions other languages but the sentiment is clearly for Ruby.

VALIDATION RULES:
1. First check the user's QUOTE against the content policy. If it violates (including being negative about Ruby), reject immediately with reject_reason "quote".
Expand Down
51 changes: 51 additions & 0 deletions app/models/concerns/testimonial/screenable.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Deterministic gate that runs before any AI call. Catches the two things the
# LLM validator kept waving through: quotes carrying links or contact details,
# and quotes that are a services pitch rather than "here is why I love Ruby".
module Testimonial::Screenable
extend ActiveSupport::Concern

URL = %r{https?://|\bwww\.}i
EMAIL = /\b[\w.+-]+@[\w-]+\.[a-z]{2,}\b/i
HANDLE = /(?:\A|\s)@[\w-]{2,}/
# Bare domains, but only on TLDs people actually advertise with, so "Ruby 1.8"
# and "rails.application.config" stay clear.
DOMAIN = /\b[a-z0-9][\w-]*\.(?:com|net|org|io|dev|app|co|ai|me|xyz|team|fm|ch|info)\b/i

PITCH = [
/\b(?:visit|check\s+out|follow|subscribe\s+to|read)\s+(?:my|our|us\s+at)\b/i,
/\b(?:hire|email|contact|dm|message|reach\s+out\s+to)\s+me\b/i,
/\bi\s+help\s+\w+(?:\s+\w+){0,3}\s+(?:build|scale|ship|grow|launch)\b/i,
/\bwe\s+(?:help|build|ship|scale)\s+(?:you|your|founders|teams|clients|companies)\b/i,
/\blet'?s\s+(?:build|work|talk|connect)\b/i,
/\b(?:available|open)\s+for\s+(?:hire|work|projects|contracts|opportunities)\b/i,
/\bneed\s+help\s+with\s+yours\b/i
].freeze

included do
validate :quote_is_not_self_promotional, if: -> { quote.present? }
end

def self_promotional? = screening_feedback.present?

# Nil when the quote is clean, otherwise the reason to show the author.
# Keyed on the quote so editing the text in memory re-screens it.
def screening_feedback
@screening ||= {}
@screening.fetch(quote) { @screening[quote] = detect_self_promotion }
end

private

def detect_self_promotion
text = quote.to_s
return I18n.t("testimonials.screening.link") if text.match?(URL) || text.match?(EMAIL) ||
text.match?(HANDLE) || text.match?(DOMAIN)
return I18n.t("testimonials.screening.promotion") if PITCH.any? { |p| text.match?(p) }

nil
end

def quote_is_not_self_promotional
errors.add(:quote, screening_feedback) if self_promotional?
end
end
4 changes: 2 additions & 2 deletions app/models/concerns/user/github_syncable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def sync_github_data_from_oauth!(auth_data)
username: auth_data.info.nickname,
email: auth_data.info.email,
name: raw_info.name || name,
bio: raw_info.bio || bio,
bio: raw_info.bio.presence || bio,
company: raw_info.company,
website: raw_info.blog.presence || website,
twitter: raw_info.twitter_username.presence || twitter,
Expand Down Expand Up @@ -228,7 +228,7 @@ def update_user_from_graphql(user, profile_data, repos_data)
username: profile_data[:login],
email: profile_data[:email] || user.email,
name: profile_data[:name] || user.name,
bio: profile_data[:bio] || user.bio,
bio: profile_data[:bio].presence || user.bio,
company: profile_data[:company],
website: profile_data[:websiteUrl].presence || user.website,
twitter: profile_data[:twitterUsername].presence || user.twitter,
Expand Down
6 changes: 6 additions & 0 deletions app/models/model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ def recalculate_total_cost!
update_column(:total_cost, chats.sum(:total_cost))
end

# The same model_id exists once per provider, so pick a provider that is
# actually configured — otherwise the call fails at request time.
def self.resolve(model_id)
enabled.find_by(model_id: model_id) || find_by(model_id: model_id)
end

def self.configured_providers
distinct.pluck(:provider).select do |provider|
Setting.provider_configured?(provider)
Expand Down
1 change: 1 addition & 0 deletions app/models/setting.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ class Setting < ApplicationRecord
DEFAULT_AI_MODEL = "gpt-4.1-nano"

ALLOWED_KEYS = %i[
carto_api_key
default_ai_model
github_api_token
github_rubycommunity_client_id github_rubycommunity_client_secret
Expand Down
13 changes: 11 additions & 2 deletions app/models/testimonial.rb
Original file line number Diff line number Diff line change
@@ -1,16 +1,25 @@
class Testimonial < ApplicationRecord
include Testimonial::AiGeneratable
include Testimonial::AiTranslatable
include Testimonial::AiValidatable
include Testimonial::Screenable

belongs_to :user

validates :quote, length: { minimum: 140, maximum: 320 }, allow_blank: true
# System writes (translation, admin backfills) set this so a longer English
# translation is never rejected — and never trimmed — by the authoring cap.
attr_accessor :system_generated

# The 140-320 range is an authoring guide for the submission form. System
# writes (translation, admin rewrites) are exempt: a faithful translation may
# land either side of the range and must never be padded or trimmed to fit.
validates :quote, length: { minimum: 140, maximum: 320 }, allow_blank: true, unless: :system_generated
validates :user_id, uniqueness: true

scope :published, -> { where(published: true) }
scope :ordered, -> { order(Arel.sql("position ASC NULLS LAST, created_at DESC")) }

after_save :process_quote_change, if: -> { saved_change_to_quote? }
after_save :process_quote_change, if: -> { saved_change_to_quote? && !system_generated }

private

Expand Down
15 changes: 15 additions & 0 deletions app/views/madmin/settings/edit.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,21 @@
</div>
</div>

<%# Map %>
<div class="bg-dark-900 py-8 px-6 rounded-xl border border-dark-700">
<h2 class="text-xl font-semibold text-dark-100 mb-6"><%= t(".map") %></h2>
<div class="space-y-4">
<div>
<%= form.label :carto_api_key, t(".carto_api_key"), class: "block text-sm font-medium text-dark-200 mb-2" %>
<%= form.password_field :carto_api_key,
value: @setting.carto_api_key,
placeholder: t(".key_placeholder"),
class: "w-full px-4 py-3 border border-dark-600 bg-dark-800 text-dark-100 rounded-lg focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 focus:outline-none transition-all placeholder-dark-500 font-mono text-sm" %>
<p class="mt-1 text-xs text-dark-500"><%= t(".carto_api_key_hint") %></p>
</div>
</div>
</div>

<%# Stripe %>
<div class="bg-dark-900 py-8 px-6 rounded-xl border border-dark-700">
<h2 class="text-xl font-semibold text-dark-100 mb-6"><%= t(".stripe") %></h2>
Expand Down
Loading