diff --git a/.ruby-version b/.ruby-version index 1454f6e..c4e41f9 100644 --- a/.ruby-version +++ b/.ruby-version @@ -1 +1 @@ -4.0.1 +4.0.3 diff --git a/Gemfile.lock b/Gemfile.lock index 298bbd1..942f4d5 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -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) @@ -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 diff --git a/app/controllers/madmin/settings_controller.rb b/app/controllers/madmin/settings_controller.rb index 981c87d..05e45ea 100644 --- a/app/controllers/madmin/settings_controller.rb +++ b/app/controllers/madmin/settings_controller.rb @@ -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, diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 0de65b2..1a92caa 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -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}" diff --git a/app/javascript/controllers/community_map_controller.js b/app/javascript/controllers/community_map_controller.js index 3cc01e9..0b6dbcc 100644 --- a/app/javascript/controllers/community_map_controller.js +++ b/app/javascript/controllers/community_map_controller.js @@ -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: {} } } @@ -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 @@ -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: '© OpenStreetMap © CARTO', subdomains: "abcd", maxZoom: 20 diff --git a/app/jobs/generate_testimonial_job.rb b/app/jobs/generate_testimonial_job.rb index 51e9b26..66c6918 100644 --- a/app/jobs/generate_testimonial_job.rb +++ b/app/jobs/generate_testimonial_job.rb @@ -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 diff --git a/app/models/concerns/post/ai_summarizable.rb b/app/models/concerns/post/ai_summarizable.rb index 70f587d..0056bdb 100644 --- a/app/models/concerns/post/ai_summarizable.rb +++ b/app/models/concerns/post/ai_summarizable.rb @@ -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}" diff --git a/app/models/concerns/testimonial/ai_generatable.rb b/app/models/concerns/testimonial/ai_generatable.rb index 6788b7c..2545d9b 100644 --- a/app/models/concerns/testimonial/ai_generatable.rb +++ b/app/models/concerns/testimonial/ai_generatable.rb @@ -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) @@ -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 diff --git a/app/models/concerns/testimonial/ai_translatable.rb b/app/models/concerns/testimonial/ai_translatable.rb new file mode 100644 index 0000000..ffc0828 --- /dev/null +++ b/app/models/concerns/testimonial/ai_translatable.rb @@ -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 diff --git a/app/models/concerns/testimonial/ai_validatable.rb b/app/models/concerns/testimonial/ai_validatable.rb index 9556db0..b42d54f 100644 --- a/app/models/concerns/testimonial/ai_validatable.rb +++ b/app/models/concerns/testimonial/ai_validatable.rb @@ -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}") @@ -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". diff --git a/app/models/concerns/testimonial/screenable.rb b/app/models/concerns/testimonial/screenable.rb new file mode 100644 index 0000000..68e2d45 --- /dev/null +++ b/app/models/concerns/testimonial/screenable.rb @@ -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 diff --git a/app/models/concerns/user/github_syncable.rb b/app/models/concerns/user/github_syncable.rb index d8ead15..f817c5b 100644 --- a/app/models/concerns/user/github_syncable.rb +++ b/app/models/concerns/user/github_syncable.rb @@ -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, @@ -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, diff --git a/app/models/model.rb b/app/models/model.rb index 74a2e86..cf96630 100644 --- a/app/models/model.rb +++ b/app/models/model.rb @@ -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) diff --git a/app/models/setting.rb b/app/models/setting.rb index ea8f2b3..78eb59d 100644 --- a/app/models/setting.rb +++ b/app/models/setting.rb @@ -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 diff --git a/app/models/testimonial.rb b/app/models/testimonial.rb index 78d1d8c..d6315cc 100644 --- a/app/models/testimonial.rb +++ b/app/models/testimonial.rb @@ -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 diff --git a/app/views/madmin/settings/edit.html.erb b/app/views/madmin/settings/edit.html.erb index c590fbe..5da7295 100644 --- a/app/views/madmin/settings/edit.html.erb +++ b/app/views/madmin/settings/edit.html.erb @@ -45,6 +45,21 @@ + <%# Map %> +
+

<%= t(".map") %>

+
+
+ <%= 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" %> +

<%= t(".carto_api_key_hint") %>

+
+
+
+ <%# Stripe %>

<%= t(".stripe") %>

diff --git a/app/views/madmin/settings/show.html.erb b/app/views/madmin/settings/show.html.erb index bd41b06..960a6f2 100644 --- a/app/views/madmin/settings/show.html.erb +++ b/app/views/madmin/settings/show.html.erb @@ -71,6 +71,25 @@
+ <%# Map %> +
+

<%= t(".map") %>

+
+
+
<%= t(".carto_api_key") %>
+
+ <% if @setting.carto_api_key.present? %> + + <%= mask_secret(@setting.carto_api_key) %> + <% else %> + + <%= t(".not_configured") %> + <% end %> +
+
+
+
+ <%# Stripe %>

<%= t(".stripe") %>

diff --git a/app/views/testimonials/_form_fields.html.erb b/app/views/testimonials/_form_fields.html.erb index f543dbd..0cd3d9c 100644 --- a/app/views/testimonials/_form_fields.html.erb +++ b/app/views/testimonials/_form_fields.html.erb @@ -3,7 +3,6 @@ <%= f.text_area :quote, rows: 4, - maxlength: 320, disabled: processing, placeholder: "I love Ruby because... (140-320 characters, or leave empty to unpublish)", data: { controller: controllers, char_counter_target: "input", action: "input->char-counter#update input->auto-resize#resize" }, diff --git a/app/views/users/index.html.erb b/app/views/users/index.html.erb index 6e687c8..0d8f705 100644 --- a/app/views/users/index.html.erb +++ b/app/views/users/index.html.erb @@ -4,6 +4,7 @@
data-community-map-fit-bounds-value="<%= @filter_geo_bounds.to_json %>"<% end %>>
diff --git a/config/locales/en/views/madmin/settings.yml b/config/locales/en/views/madmin/settings.yml index 7720680..710abd4 100644 --- a/config/locales/en/views/madmin/settings.yml +++ b/config/locales/en/views/madmin/settings.yml @@ -28,6 +28,10 @@ en: validation_model: Validation Model edit: cancel: Cancel + carto_api_key: CARTO API Key + carto_api_key_hint: Basemap tiles for the community map. Without a key CARTO + watermarks every tile. Get one at carto.com/basemaps/apikey and restrict + it to your domains. github: GitHub github_api_token: API Token github_api_token_hint: Used for batch syncing GitHub profile data and repositories. @@ -42,6 +46,7 @@ en: litestream_replica_bucket: Replica Bucket litestream_replica_key_id: Access Key ID litestream_restart_note: Changes to Litestream settings require a server restart. + map: Map save: Save Settings stripe: Stripe stripe_publishable_key: Publishable Key @@ -51,6 +56,7 @@ en: trial_days_hint: Number of days new teams get as a free trial. Set to 0 to disable. show: + carto_api_key: CARTO API Key edit_button: Edit Settings github: GitHub github_api_token: API Token @@ -64,6 +70,7 @@ en: litestream_replica_bucket: Replica Bucket litestream_replica_key_id: Access Key ID litestream_restart_note: Changes to Litestream settings require a server restart. + map: Map not_configured: Not configured stripe: Stripe stripe_publishable_key: Publishable Key diff --git a/config/locales/en/views/testimonials.yml b/config/locales/en/views/testimonials.yml new file mode 100644 index 0000000..4007ad9 --- /dev/null +++ b/config/locales/en/views/testimonials.yml @@ -0,0 +1,8 @@ +--- +en: + testimonials: + screening: + link: please remove links, email addresses and @handles — this is a place for + why you love Ruby, not for promoting a site or profile + promotion: please rewrite this as a personal testimonial about Ruby rather than + a pitch for your services diff --git a/db/migrate/20260828174730_add_translation_fields_to_testimonials.rb b/db/migrate/20260828174730_add_translation_fields_to_testimonials.rb new file mode 100644 index 0000000..16cdfb8 --- /dev/null +++ b/db/migrate/20260828174730_add_translation_fields_to_testimonials.rb @@ -0,0 +1,6 @@ +class AddTranslationFieldsToTestimonials < ActiveRecord::Migration[8.2] + def change + add_column :testimonials, :quote_original, :text + add_column :testimonials, :quote_language, :string + end +end diff --git a/db/migrate/20260909214500_add_carto_api_key_to_settings.rb b/db/migrate/20260909214500_add_carto_api_key_to_settings.rb new file mode 100644 index 0000000..77c1e3f --- /dev/null +++ b/db/migrate/20260909214500_add_carto_api_key_to_settings.rb @@ -0,0 +1,5 @@ +class AddCartoApiKeyToSettings < ActiveRecord::Migration[8.2] + def change + add_column :settings, :carto_api_key, :string + end +end diff --git a/db/schema.rb b/db/schema.rb index 5532af8..325982e 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[8.2].define(version: 2026_04_08_170000) do +ActiveRecord::Schema[8.2].define(version: 2026_09_09_214500) do create_table "_litestream_lock", id: false, force: :cascade do |t| t.integer "id" end @@ -277,6 +277,182 @@ t.index ["provider", "key"], name: "index_provider_credentials_on_provider_and_key", unique: true end + create_table "rails_error_dashboard_applications", force: :cascade do |t| + t.datetime "created_at" + t.text "description" + t.string "name", limit: 255, null: false + t.datetime "updated_at" + t.index ["name"], name: "index_rails_error_dashboard_applications_on_name", unique: true + end + + create_table "rails_error_dashboard_cascade_patterns", force: :cascade do |t| + t.float "avg_delay_seconds" + t.float "cascade_probability" + t.bigint "child_error_id", null: false + t.datetime "created_at", null: false + t.integer "frequency", default: 1, null: false + t.datetime "last_detected_at" + t.bigint "parent_error_id", null: false + t.datetime "updated_at", null: false + t.index ["cascade_probability"], name: "index_cascade_patterns_on_probability" + t.index ["child_error_id"], name: "index_cascade_patterns_on_child" + t.index ["parent_error_id", "child_error_id"], name: "index_cascade_patterns_on_parent_and_child", unique: true + t.index ["parent_error_id"], name: "index_cascade_patterns_on_parent" + end + + create_table "rails_error_dashboard_diagnostic_dumps", force: :cascade do |t| + t.integer "application_id", null: false + t.datetime "captured_at", null: false + t.datetime "created_at", null: false + t.text "dump_data", null: false + t.string "note" + t.datetime "updated_at", null: false + t.index ["application_id"], name: "index_rails_error_dashboard_diagnostic_dumps_on_application_id" + t.index ["captured_at"], name: "index_diagnostic_dumps_on_captured_at" + end + + create_table "rails_error_dashboard_error_baselines", force: :cascade do |t| + t.string "baseline_type", null: false + t.integer "count", default: 0, null: false + t.datetime "created_at", null: false + t.string "error_type", null: false + t.float "mean" + t.float "percentile_95" + t.float "percentile_99" + t.datetime "period_end", null: false + t.datetime "period_start", null: false + t.string "platform", null: false + t.integer "sample_size", default: 0, null: false + t.float "std_dev" + t.datetime "updated_at", null: false + t.index ["error_type", "platform", "baseline_type", "period_start"], name: "index_error_baselines_on_type_platform_baseline_period" + t.index ["error_type", "platform"], name: "index_error_baselines_on_error_type_and_platform" + t.index ["period_end"], name: "index_error_baselines_on_period_end" + end + + create_table "rails_error_dashboard_error_comments", force: :cascade do |t| + t.string "author_name", null: false + t.text "body", null: false + t.datetime "created_at", null: false + t.bigint "error_log_id", null: false + t.datetime "updated_at", null: false + t.index ["error_log_id", "created_at"], name: "index_error_comments_on_error_and_time" + t.index ["error_log_id"], name: "index_rails_error_dashboard_error_comments_on_error_log_id" + end + + create_table "rails_error_dashboard_error_logs", force: :cascade do |t| + t.string "action_name" + t.string "app_version" + t.bigint "application_id", null: false + t.datetime "assigned_at" + t.string "assigned_to" + t.text "backtrace" + t.string "backtrace_signature" + t.text "breadcrumbs" + t.string "content_type", limit: 100 + t.string "controller_name" + t.datetime "created_at", null: false + t.text "environment_info" + t.string "error_hash" + t.string "error_type", null: false + t.text "exception_cause" + t.integer "external_issue_number" + t.string "external_issue_provider", limit: 20 + t.string "external_issue_url" + t.datetime "first_seen_at" + t.string "git_sha" + t.string "hostname", limit: 255 + t.string "http_method", limit: 10 + t.text "instance_variables" + t.string "ip_address" + t.datetime "last_seen_at" + t.text "local_variables" + t.text "message", null: false + t.boolean "muted", default: false, null: false + t.datetime "muted_at" + t.string "muted_by" + t.string "muted_reason" + t.datetime "occurred_at", null: false + t.integer "occurrence_count", default: 1, null: false + t.string "platform" + t.integer "priority_level", default: 0 + t.integer "priority_score" + t.datetime "reopened_at" + t.integer "request_duration_ms" + t.text "request_params" + t.text "request_url" + t.text "resolution_comment" + t.string "resolution_reference" + t.boolean "resolved", default: false, null: false + t.datetime "resolved_at" + t.string "resolved_by_name" + t.float "similarity_score" + t.datetime "snoozed_until" + t.string "status", default: "new" + t.text "system_health" + t.datetime "updated_at", null: false + t.text "user_agent" + t.integer "user_id" + t.index ["app_version", "resolved", "occurred_at"], name: "index_error_logs_on_version_resolution_time" + t.index ["app_version"], name: "index_rails_error_dashboard_error_logs_on_app_version" + t.index ["application_id", "occurred_at"], name: "index_error_logs_on_app_occurred" + t.index ["application_id", "resolved"], name: "index_error_logs_on_app_resolved" + t.index ["application_id"], name: "index_rails_error_dashboard_error_logs_on_application_id" + t.index ["assigned_to", "status", "occurred_at"], name: "index_error_logs_on_assignment_workflow" + t.index ["backtrace_signature"], name: "index_rails_error_dashboard_error_logs_on_backtrace_signature" + t.index ["controller_name", "action_name", "error_hash"], name: "index_error_logs_on_controller_action_hash" + t.index ["error_hash", "resolved", "occurred_at"], name: "index_error_logs_on_hash_resolved_occurred" + t.index ["error_hash"], name: "index_rails_error_dashboard_error_logs_on_error_hash" + t.index ["error_type", "occurred_at"], name: "index_error_logs_on_error_type_and_occurred_at" + t.index ["error_type"], name: "index_rails_error_dashboard_error_logs_on_error_type" + t.index ["first_seen_at"], name: "index_rails_error_dashboard_error_logs_on_first_seen_at" + t.index ["git_sha"], name: "index_rails_error_dashboard_error_logs_on_git_sha" + t.index ["last_seen_at"], name: "index_rails_error_dashboard_error_logs_on_last_seen_at" + t.index ["muted"], name: "index_rails_error_dashboard_error_logs_on_muted" + t.index ["occurred_at"], name: "index_rails_error_dashboard_error_logs_on_occurred_at" + t.index ["occurrence_count"], name: "index_rails_error_dashboard_error_logs_on_occurrence_count" + t.index ["platform", "occurred_at"], name: "index_error_logs_on_platform_and_occurred_at" + t.index ["platform", "status", "occurred_at"], name: "index_error_logs_on_platform_status_time" + t.index ["platform"], name: "index_rails_error_dashboard_error_logs_on_platform" + t.index ["priority_level", "resolved", "occurred_at"], name: "index_error_logs_on_priority_resolution" + t.index ["priority_score"], name: "index_rails_error_dashboard_error_logs_on_priority_score" + t.index ["resolved", "occurred_at"], name: "index_error_logs_on_resolved_and_occurred_at" + t.index ["resolved"], name: "index_rails_error_dashboard_error_logs_on_resolved" + t.index ["similarity_score"], name: "index_rails_error_dashboard_error_logs_on_similarity_score" + t.index ["user_id"], name: "index_rails_error_dashboard_error_logs_on_user_id" + end + + create_table "rails_error_dashboard_error_occurrences", force: :cascade do |t| + t.datetime "created_at", null: false + t.bigint "error_log_id", null: false + t.datetime "occurred_at", null: false + t.string "request_id" + t.string "session_id" + t.datetime "updated_at", null: false + t.integer "user_id" + t.index ["error_log_id"], name: "index_error_occurrences_on_error_log" + t.index ["occurred_at", "error_log_id"], name: "index_error_occurrences_on_time_and_error" + t.index ["request_id"], name: "index_error_occurrences_on_request" + t.index ["user_id"], name: "index_error_occurrences_on_user" + end + + create_table "rails_error_dashboard_swallowed_exceptions", force: :cascade do |t| + t.bigint "application_id" + t.datetime "created_at", null: false + t.string "exception_class", limit: 250, null: false + t.datetime "last_seen_at" + t.datetime "period_hour", null: false + t.integer "raise_count", default: 0, null: false + t.string "raise_location", limit: 250, null: false + t.integer "rescue_count", default: 0, null: false + t.string "rescue_location", limit: 250 + t.datetime "updated_at", null: false + t.index ["application_id", "period_hour"], name: "index_swallowed_exceptions_on_app_and_hour" + t.index ["exception_class", "period_hour"], name: "index_swallowed_exceptions_on_class_and_hour" + t.index ["exception_class", "raise_location", "rescue_location", "period_hour", "application_id"], name: "index_swallowed_exceptions_upsert_key", unique: true + t.index ["period_hour"], name: "index_swallowed_exceptions_on_period_hour" + end + create_table "reports", id: :string, default: -> { "uuid7()" }, force: :cascade do |t| t.datetime "created_at", null: false t.text "description" @@ -290,6 +466,7 @@ end create_table "settings", id: :string, default: -> { "uuid7()" }, force: :cascade do |t| + t.string "carto_api_key" t.datetime "created_at", null: false t.string "default_ai_model" t.string "github_api_token" @@ -372,6 +549,8 @@ t.integer "position" t.boolean "published", default: false t.text "quote" + t.string "quote_language" + t.text "quote_original" t.string "reject_reason" t.string "subheading" t.datetime "updated_at", null: false @@ -460,6 +639,12 @@ add_foreign_key "posts_tags", "posts" add_foreign_key "posts_tags", "tags" add_foreign_key "projects", "users" + add_foreign_key "rails_error_dashboard_cascade_patterns", "rails_error_dashboard_error_logs", column: "child_error_id" + add_foreign_key "rails_error_dashboard_cascade_patterns", "rails_error_dashboard_error_logs", column: "parent_error_id" + add_foreign_key "rails_error_dashboard_diagnostic_dumps", "rails_error_dashboard_applications", column: "application_id" + add_foreign_key "rails_error_dashboard_error_comments", "rails_error_dashboard_error_logs", column: "error_log_id" + add_foreign_key "rails_error_dashboard_error_logs", "rails_error_dashboard_applications", column: "application_id" + add_foreign_key "rails_error_dashboard_error_occurrences", "rails_error_dashboard_error_logs", column: "error_log_id" add_foreign_key "reports", "posts" add_foreign_key "reports", "users" add_foreign_key "star_snapshots", "projects" diff --git a/lib/tasks/book.rake b/lib/tasks/book.rake new file mode 100644 index 0000000..f88f65f --- /dev/null +++ b/lib/tasks/book.rake @@ -0,0 +1,727 @@ +# frozen_string_literal: true + +require "base64" + +namespace :book do + # Featured testimonials appear first, in this order. Everything else follows in default order. + FEATURED_USERNAMES = %w[matz dhh pragdave AmandaPerino].freeze + + # Usernames whose testimonials should be excluded from the book output. + # Kept here (rather than unpublished in the DB) so authors can still edit/resubmit on the site. + EXCLUDED_USERNAMES = %w[rubyon].freeze + + # Print specs (European printshop, per whyruby.info book contract). + TRIM_WIDTH_MM = 170 + TRIM_HEIGHT_MM = 240 + BLEED_MM = 3 + PAGE_WIDTH_MM = TRIM_WIDTH_MM + BLEED_MM * 2 # 176 + PAGE_HEIGHT_MM = TRIM_HEIGHT_MM + BLEED_MM * 2 # 246 + + # We look for a European coated CMYK profile inside vendor/icc/. Fogra51 + # (PSO Coated v3) is preferred — it's ECI's current recommended default and + # models OBA-brightened stocks accurately. Fogra39 (ISO Coated v2) is kept + # as a fallback since a lot of shops still calibrate against it. The ECI + # files aren't redistributable, so users drop them in themselves. + PREFERRED_ICC_NAMES = %w[ + PSOcoated_v3.icc + PSOcoated_v3_FOGRA51.icc + ISOcoated_v2_eci.icc + ISOcoated_v2_300_eci.icc + Coated_Fogra39L_VIGC_300.icc + FOGRA39.icc + ].freeze + + desc "Generate 'Why Ruby?' as HTML + print-ready PDF (176×246mm, CMYK, text-to-curves, PDF/X-1a)" + task generate: :environment do + testimonials = ordered_testimonials_for_book + + if testimonials.empty? + puts "No published testimonials found. Nothing to generate." + exit 0 + end + + html = build_book_html(testimonials) + html_path = Rails.root.join("tmp", "why_ruby_book.html") + File.write(html_path, html) + + puts "Generated book with #{testimonials.size} testimonials (#{book_page_count(testimonials)} pages, even-padded)" + puts "HTML: #{html_path}" + + raw_pdf_path = Rails.root.join("tmp", "why_ruby_book_raw.pdf") + final_pdf_path = Rails.root.join("tmp", "why_ruby_book.pdf") + + unless render_chrome_pdf(html_path, raw_pdf_path) + puts "Chrome PDF step failed — skipping post-processing." + next + end + + if postprocess_pdf_for_print(raw_pdf_path, final_pdf_path) + File.delete(raw_pdf_path) if File.exist?(raw_pdf_path) + puts "PDF: #{final_pdf_path}" + puts " → CMYK · text outlined to curves · PDF/X-1a · 176×246mm (170×240 trim + 3mm bleed)" + else + File.rename(raw_pdf_path, final_pdf_path) if File.exist?(raw_pdf_path) + puts "PDF: #{final_pdf_path} (raw Chrome output — post-processing skipped/failed)" + end + end + + private + + def ordered_testimonials_for_book + all = Testimonial.published.ordered.includes(:user).to_a + all.reject! { |t| EXCLUDED_USERNAMES.include?(t.user.username) } + featured_by_username = all.each_with_object({}) do |t, acc| + acc[t.user.username] = t if FEATURED_USERNAMES.include?(t.user.username) + end + featured = FEATURED_USERNAMES.map { |u| featured_by_username[u] }.compact + rest = (all - featured).shuffle + featured + rest + end + + def render_chrome_pdf(html_path, pdf_path) + chrome = detect_chrome_binary + unless chrome + puts "Chrome/Chromium not found — cannot generate PDF." + puts "Install Chrome, or open the HTML in your browser and use File → Print → Save as PDF." + return false + end + + ok = system( + chrome, + "--headless=new", + "--disable-gpu", + "--no-sandbox", + "--no-pdf-header-footer", + "--print-to-pdf-no-header", + "--print-to-pdf=#{pdf_path}", + "file://#{html_path}" + ) + + ok && File.exist?(pdf_path) + end + + # Post-process Chrome's PDF into a print-ready PDF/X-1a: + # • All glyphs outlined to curves (-dNoOutputFonts) — kills Affinity's + # "broken font" import problem since there are no fonts in the file + # to break in the first place. + # • RGB → CMYK conversion with a Fogra39-family output intent when the + # ECI ICC profile is available under vendor/icc/, otherwise Ghostscript's + # default CMYK profile (US-SWOP-ish; visually close for proofing). + # • /prepress preset keeps images at 300 DPI and honors overprint. + def postprocess_pdf_for_print(input_path, output_path) + gs = detect_ghostscript + unless gs + puts "Ghostscript not found — skipping print-ready post-processing." + puts "Install with: brew install ghostscript (macOS) or apt install ghostscript (Debian/Ubuntu)" + return false + end + + icc_path, icc_source = resolve_output_icc_profile + unless icc_path + puts "No CMYK ICC profile available — skipping post-processing." + return false + end + pdfx_def_path = write_pdfx_def(icc_path) + + intent = output_intent_metadata(icc_path) + puts "Post-processing PDF via Ghostscript" + if icc_source == :fogra + puts " Output intent: #{File.basename(icc_path)} (#{intent[:identifier]})" + else + puts " Output intent: Ghostscript default CMYK (drop PSOcoated_v3.icc into" + puts " vendor/icc/ from https://www.eci.org for a fully" + puts " spec-compliant Fogra51 PDF/X-1a; download is free)." + end + + # Ghostscript 9.28+ SAFER mode needs an explicit allowlist for anything + # outside the working dir — the ICC profile especially, since it typically + # lives under /opt/homebrew or /usr/share. + ok = system( + gs, + "-dNOPAUSE", "-dBATCH", "-dSAFER", "-dQUIET", + "--permit-file-read=#{icc_path}", + "--permit-file-read=#{pdfx_def_path}", + "--permit-file-read=#{input_path}", + "--permit-file-write=#{output_path}", + "-sDEVICE=pdfwrite", + "-dCompatibilityLevel=1.6", + "-dPDFX=1", + "-dNoOutputFonts", + "-sProcessColorModel=DeviceCMYK", + "-sColorConversionStrategy=CMYK", + "-dPDFSETTINGS=/prepress", + "-dEmbedAllFonts=true", + "-dSubsetFonts=true", + "-dDetectDuplicateImages=true", + "-sOutputICCProfile=#{icc_path}", + "-sOutputFile=#{output_path}", + pdfx_def_path.to_s, + input_path.to_s + ) + + File.delete(pdfx_def_path) if File.exist?(pdfx_def_path) + + unless ok && File.exist?(output_path) + puts " Ghostscript post-processing failed — see errors above." + return false + end + + true + end + + def detect_chrome_binary + [ + "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", + "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary", + "/Applications/Chromium.app/Contents/MacOS/Chromium", + "/opt/homebrew/bin/chromium", + "/usr/bin/google-chrome", + "/usr/bin/chromium", + "/usr/bin/chromium-browser" + ].find { |path| File.executable?(path) } + end + + def detect_ghostscript + return ENV["GS_BIN"] if ENV["GS_BIN"] && File.executable?(ENV["GS_BIN"]) + + %w[ + /opt/homebrew/bin/gs + /usr/local/bin/gs + /usr/bin/gs + ].find { |path| File.executable?(path) } + end + + def resolve_output_icc_profile + vendor_icc = Rails.root.join("vendor", "icc") + preferred = PREFERRED_ICC_NAMES.map { |name| vendor_icc.join(name) }.find { |p| File.exist?(p) } + return [ preferred.to_s, :fogra ] if preferred + + default_cmyk = Dir.glob([ + "/opt/homebrew/share/ghostscript/*/iccprofiles/default_cmyk.icc", + "/usr/local/share/ghostscript/*/iccprofiles/default_cmyk.icc", + "/usr/share/ghostscript/*/iccprofiles/default_cmyk.icc" + ]).first + + default_cmyk ? [ default_cmyk, :default ] : [ nil, :missing ] + end + + # Adapted from Ghostscript's stock PDFX_def.ps, hard-coded for PDF/X-1a. The + # OutputConditionIdentifier / Info are derived from the actual embedded ICC + # so metadata stays consistent (Fogra51 profile → FOGRA51 tag, etc.). If we + # fall back to gs's default CMYK, we tag it Fogra51 as the safest modern + # default — the printshop will resolve against their own calibration anyway. + def write_pdfx_def(icc_path) + escaped_icc = icc_path.to_s.gsub("(", '\\(').gsub(")", '\\)') + intent = output_intent_metadata(icc_path) + + body = <<~PS + %! + % Generated PDF/X-1a header for the 'Why Ruby?' book. + + systemdict /ColorConversionStrategy known { + systemdict /ColorConversionStrategy get cvn dup /Gray ne exch /CMYK ne and + } { + true + } ifelse + { /ColorConversionStrategy cvx /rangecheck signalerror + } if + + [ /GTS_PDFXVersion (PDF/X-1a:2001) + /Title (Why Ruby?) + /Trapped /False + /DOCINFO pdfmark + + /ICCProfile (#{escaped_icc}) def + + [/_objdef {icc_PDFX} /type /stream /OBJ pdfmark + [{icc_PDFX} << /N 4 >> /PUT pdfmark + [{icc_PDFX} ICCProfile (r) file /PUT pdfmark + + [/_objdef {OutputIntent_PDFX} /type /dict /OBJ pdfmark + [{OutputIntent_PDFX} << + /Type /OutputIntent + /S /GTS_PDFX + /OutputCondition (Commercial offset printing, Europe) + /Info (#{intent[:info]}) + /OutputConditionIdentifier (#{intent[:identifier]}) + /RegistryName (http://www.color.org) + /DestOutputProfile {icc_PDFX} + >> /PUT pdfmark + [{Catalog} <> /PUT pdfmark + PS + + path = Rails.root.join("tmp", "why_ruby_pdfx_def.ps") + File.write(path, body) + path + end + + def output_intent_metadata(icc_path) + name = File.basename(icc_path.to_s).downcase + if name.include?("psocoated_v3") || name.include?("fogra51") + { identifier: "FOGRA51", info: "Coated FOGRA51 \\(PSO Coated v3, ISO 12647-2:2013\\)" } + elsif name.include?("isocoated_v2") || name.include?("fogra39") + { identifier: "FOGRA39", info: "Coated FOGRA39 \\(ISO Coated v2, ISO 12647-2:2004\\)" } + else + # Unknown/default profile — tag as Fogra51 (current ECI recommendation). + { identifier: "FOGRA51", info: "Coated FOGRA51 \\(PSO Coated v3, ISO 12647-2:2013\\)" } + end + end + + # Front matter is 2 pages (title + colophon), back matter is 1 page. + # Printshops need an even total, so we drop a blank leaf before the back + # cover if the count comes out odd. + def book_page_count(testimonials) + base = 2 + testimonials.size + 1 + base.odd? ? base + 1 : base + end + + def build_book_html(testimonials) + base_pages = 2 + testimonials.size + 1 + padding_page = base_pages.odd? ? blank_page : "" + + <<~HTML + + + + + + Why Ruby? + + + + + + + #{title_page} + #{colophon_page} + #{testimonials.map { |t| testimonial_page(t) }.join("\n")} + #{padding_page} + #{back_page} + + + HTML + end + + def blank_page + %(
) + end + + def book_css + <<~CSS + @page { + size: 176mm 246mm; + margin: 0; + } + + *, *::before, *::after { + box-sizing: border-box; + margin: 0; + padding: 0; + } + + html, body { + margin: 0; + padding: 0; + background: #fff; + -webkit-print-color-adjust: exact; + print-color-adjust: exact; + } + + body { + font-family: "Inter", system-ui, -apple-system, sans-serif; + color: #000; + line-height: 1.5; + } + + .page { + width: 176mm; + height: 246mm; + padding: 20mm 18mm; + position: relative; + overflow: hidden; + page-break-after: always; + display: flex; + flex-direction: column; + } + + .page:last-child { + page-break-after: auto; + } + + /* ── Title page ── */ + + .title-page { + justify-content: center; + align-items: center; + text-align: center; + } + + .title-page__logo { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 8mm; + font-weight: 900; + font-size: 84pt; + color: #dc2626; + line-height: 1; + letter-spacing: -0.02em; + } + + .title-page__logo-icon { + width: 44mm; + height: 44mm; + object-fit: contain; + } + + /* ── Colophon page ── */ + + .colophon-page { + justify-content: flex-end; + align-items: center; + text-align: center; + } + + .colophon-page__text { + font-size: 8.5pt; + color: #9ca3af; + letter-spacing: 0.04em; + padding-bottom: 4mm; + } + + /* ── Back page ── */ + + .back-page { + justify-content: center; + align-items: center; + text-align: center; + } + + .back-page__heart { + font-size: 14pt; + color: #6b7280; + line-height: 1.8; + } + + .back-page__url { + font-size: 9pt; + color: #9ca3af; + letter-spacing: 0.08em; + margin-top: 8mm; + } + + /* ── Testimonial page (1:1 home-carousel layout, centered on page) ── */ + + .testimonial-page { + justify-content: center; + align-items: stretch; + } + + .testimonial-inner { + display: flex; + flex-direction: column; + } + + .testimonial__heading { + font-family: Georgia, "Times New Roman", serif; + font-style: italic; + font-size: 46pt; + color: #dc2626; + line-height: 1.05; + letter-spacing: -0.02em; + margin-bottom: 6mm; + } + + .testimonial__subheading { + font-size: 18pt; + font-weight: 700; + color: #000; + line-height: 1.3; + margin-bottom: 3mm; + } + + .testimonial__body { + font-size: 11pt; + color: #6b7280; + line-height: 1.7; + margin-top: 5mm; + margin-bottom: 12mm; + } + + /* Red bordered quote box + red opening " overhanging top-left + downward tail. */ + .quote-block { + position: relative; + padding-top: 3mm; + } + + .quote-block__mark { + position: absolute; + top: -6mm; + left: -3mm; + font-family: Georgia, "Times New Roman", serif; + font-size: 60pt; + color: #dc2626; + line-height: 1; + user-select: none; + z-index: 2; + } + + .quote-block__box { + background: #fff; + border: 1.5pt solid #fecaca; + border-radius: 3mm; + padding: 8mm; + position: relative; + } + + .quote-block__text { + font-style: italic; + font-size: 12pt; + color: #4b5563; + line-height: 1.6; + } + + /* Quotes have no length cap, so the type steps down to fit the page + rather than the text ever being cut. */ + .quote-block__text--long { font-size: 11pt; line-height: 1.55; } + .quote-block__text--longer { font-size: 10pt; line-height: 1.5; } + .quote-block__text--xlong { font-size: 9pt; line-height: 1.45; } + + .quote-block__box--long { padding: 7mm; } + .quote-block__box--longer { padding: 6mm; } + .quote-block__box--xlong { padding: 5mm; } + + /* Speech-bubble tail: outer red triangle + inner white triangle, pointing down toward avatar. */ + .quote-block__box::before, + .quote-block__box::after { + content: ""; + position: absolute; + width: 0; + height: 0; + } + + /* Outer red tail apex is shifted 1 mm further left than the inner white, + so the red tail-point pokes out to the left of the white — feels more + "leaning toward" the avatar rather than perfectly stacked. */ + .quote-block__box::before { + bottom: -5mm; + left: 10.2mm; + border-left: 4mm solid transparent; + border-right: 4mm solid transparent; + border-top: 5mm solid #fecaca; + } + + .quote-block__box::after { + bottom: -4mm; + left: 9.5mm; + border-left: 5mm solid transparent; + border-right: 5mm solid transparent; + border-top: 6mm solid #fff; + } + + /* User tile — avatar left, info right (matches _user_tile.html.erb on iPad). */ + .user-tile { + display: flex; + align-items: center; + gap: 5mm; + margin-top: 8mm; + } + + .user-tile__avatar-wrap { + width: 30mm; + height: 32mm; + position: relative; + flex-shrink: 0; + } + + .user-tile__info { + flex: 1; + min-width: 0; + } + + .user-tile__name { + font-size: 16pt; + font-weight: 700; + color: #000; + line-height: 1.15; + } + + .user-tile__bio { + font-size: 9pt; + color: #6b7280; + line-height: 1.4; + margin-top: 2mm; + } + + .user-tile__meta { + font-size: 8pt; + color: #9ca3af; + line-height: 1.4; + display: flex; + flex-wrap: wrap; + gap: 3mm; + margin-top: 1.5mm; + } + + .user-tile__meta-item { + display: inline-flex; + align-items: center; + gap: 1mm; + } + + .user-tile__meta-icon { + width: 2.8mm; + height: 2.8mm; + color: #d1d5db; + fill: currentColor; + flex-shrink: 0; + } + CSS + end + + def title_page + <<~HTML +
+ +
+ HTML + end + + def colophon_page + <<~HTML +
+
whyruby.info • #{Date.current.year}
+
+ HTML + end + + def back_page + <<~HTML +
+
Made with ❤️ by the Ruby community
+
rubycommunity.org
+
+ HTML + end + + def testimonial_page(testimonial) + user = testimonial.user + subheading_html = format_subheading(testimonial.subheading) + + <<~HTML +
+
+ #{"
#{escape(testimonial.heading)}
" if testimonial.heading.present?} + #{"
#{subheading_html}
" if testimonial.subheading.present?} + #{"
#{escape(testimonial.body_text)}
" if testimonial.body_text.present?} + #{quote_block(testimonial)} + #{user_tile(user)} +
+
+ HTML + end + + # Step the quote type down as the text grows. Never truncates — the full quote + # is always printed, the page just gives it more room. + QUOTE_FIT_STEPS = [ [ 560, "xlong" ], [ 460, "longer" ], [ 360, "long" ] ].freeze + + def quote_block(testimonial) + return "" if testimonial.quote.blank? + + step = QUOTE_FIT_STEPS.find { |threshold, _| testimonial.quote.length > threshold }&.last + text_class = [ "quote-block__text", ("quote-block__text--#{step}" if step) ].compact.join(" ") + box_class = [ "quote-block__box", ("quote-block__box--#{step}" if step) ].compact.join(" ") + + <<~HTML +
+ “ +
+
#{escape(testimonial.quote)}
+
+
+ HTML + end + + def user_tile(user) + @gem_clip_counter = (@gem_clip_counter || 0) + 1 + uid = @gem_clip_counter + avatar_url = escape(user.avatar_url.to_s) + gem_path = "M56.6.55h86.84c6.79,0,13.13,3.39,16.9,9.04l36.26,54.34c5.26,7.89,4.37,18.37-2.15,25.25l-79.68,84.14c-8.01,8.46-21.49,8.46-29.51,0L5.59,89.18c-6.52-6.88-7.41-17.36-2.15-25.25L39.7,9.59C43.47,3.94,49.81.55,56.6.55Z" + + meta_items = [] + + if user.company.present? + meta_items << <<~HTML.strip + + + + + #{escape(user.company)} + + HTML + end + + if user.location.present? + meta_items << <<~HTML.strip + + + + + #{escape(user.location)} + + HTML + end + + <<~HTML +
+
+ + + + + + + #{"" if avatar_url.present?} + #{"" if avatar_url.blank?} + + + +
+
+
#{escape(user.display_name)}
+ #{"
#{escape(user.bio)}
" if user.bio.present?} + #{meta_items.any? ? "
#{meta_items.join}
" : ""} +
+
+ HTML + end + + def format_subheading(subheading) + return "" if subheading.blank? + + subheading + .split(".") + .map(&:strip) + .reject(&:blank?) + .map { |sentence| "#{escape(sentence)}." } + .join("
") + end + + def escape(text) + ERB::Util.html_escape(text.to_s) + end + + def heart_data_uri + @heart_data_uri ||= begin + path = Rails.root.join("app", "assets", "images", "heart.webp") + "data:image/webp;base64,#{Base64.strict_encode64(File.binread(path))}" + end + end +end diff --git a/lib/tasks/production_data.rake b/lib/tasks/production_data.rake index 4bfbf7c..648cde0 100644 --- a/lib/tasks/production_data.rake +++ b/lib/tasks/production_data.rake @@ -26,8 +26,8 @@ class ProductionPullConfig attr_reader :server_ip, :volume_name, :ssh_user, :dev_db_path, :storage_root def initialize - deploy = YAML.safe_load_file(Rails.root.join("config/deploy.yml"), permitted_classes: [ Symbol ]) - db_config = YAML.safe_load(ERB.new(File.read(Rails.root.join("config/database.yml"))).result, permitted_classes: [ Symbol ]) + deploy = YAML.safe_load_file(Rails.root.join("config/deploy.yml"), permitted_classes: [ Symbol ], aliases: true) + db_config = YAML.safe_load(ERB.new(File.read(Rails.root.join("config/database.yml"))).result, permitted_classes: [ Symbol ], aliases: true) @server_ip = extract_server_ip(deploy) @volume_name = extract_volume_name(deploy) diff --git a/lib/tasks/testimonials.rake b/lib/tasks/testimonials.rake index 25b8d75..e5a6903 100644 --- a/lib/tasks/testimonials.rake +++ b/lib/tasks/testimonials.rake @@ -11,4 +11,120 @@ namespace :testimonials do puts "Sent #{count} testimonial invitation emails." end + + desc "Unpublish a testimonial and tell its author why. Usage: rake 'testimonials:reject[username,reason]'" + task :reject, [ :username, :reason ] => :environment do |_t, args| + username = args[:username].presence or abort "Usage: rake 'testimonials:reject[username,reason]'" + reason = args[:reason].presence || "This testimonial was removed because it does not read as a personal statement about Ruby." + + testimonial = find_testimonial!(username) + + testimonial.update_columns( + published: false, + reject_reason: "quote", + ai_feedback: reason + ) + + puts "Unpublished #{username}." + puts " Reason shown to author: #{reason}" + puts " Quote kept in the database. Re-publish with: rake 'testimonials:publish[#{username}]'" + end + + desc "Re-publish a previously rejected testimonial. Usage: rake 'testimonials:publish[username]'" + task :publish, [ :username ] => :environment do |_t, args| + username = args[:username].presence or abort "Usage: rake 'testimonials:publish[username]'" + testimonial = find_testimonial!(username) + + testimonial.update_columns(published: true, reject_reason: nil, ai_feedback: nil) + puts "Re-published #{username}." + end + + desc "List published testimonials that trip the self-promotion screen" + task screen: :environment do + flagged = Testimonial.published.includes(:user).select(&:self_promotional?) + + if flagged.empty? + puts "No published testimonial trips the self-promotion screen." + next + end + + puts "#{flagged.size} published testimonial(s) flagged:\n\n" + flagged.each do |t| + puts " #{t.user.username}" + puts " #{t.screening_feedback}" + puts " #{t.quote.truncate(120)}" + puts " reject with: rake 'testimonials:reject[#{t.user.username}]'" + puts + end + end + + desc "Translate non-English testimonials to English, keeping the original. Usage: rake testimonials:translate or 'testimonials:translate[username]'" + task :translate, [ :username ] => :environment do |_t, args| + scope = if args[:username].present? + Testimonial.joins(:user).where(users: { username: args[:username] }) + else + Testimonial.where(quote_original: nil).where.not(quote: [ nil, "" ]) + end + + translated = 0 + scope.includes(:user).find_each do |testimonial| + next unless testimonial.needs_translation? + + if testimonial.translate_to_english! + translated += 1 + puts "Translated #{testimonial.user.username} (#{testimonial.quote_language} → en)" + puts " original: #{testimonial.quote_original.truncate(90)}" + puts " english: #{testimonial.quote.truncate(90)}" + end + end + + puts "\nTranslated #{translated} testimonial(s). Originals kept in quote_original." + puts "Run 'rake testimonials:regenerate[username]' to rewrite AI fields from the English text." if translated.positive? + end + + desc "Regenerate heading, subheading and body from the current quote. Usage: rake 'testimonials:regenerate[username]'" + task :regenerate, [ :username ] => :environment do |_t, args| + username = args[:username].presence or abort "Usage: rake 'testimonials:regenerate[username]'" + testimonial = find_testimonial!(username) + + puts "Regenerating for #{username}..." + testimonial.update_columns(ai_attempts: 0, ai_feedback: nil, reject_reason: nil) + testimonial.generate_ai_fields! + testimonial.reload + + puts " heading: #{testimonial.heading}" + puts " subheading: #{testimonial.subheading}" + puts " body: #{testimonial.body_text}" + puts " published: #{testimonial.published?}" + end + + desc "Replace a quote and regenerate everything from it. Usage: rake 'testimonials:rewrite[username,new quote text]'" + task :rewrite, [ :username, :quote ] => :environment do |_t, args| + username = args[:username].presence or abort "Usage: rake 'testimonials:rewrite[username,new quote]'" + new_quote = args[:quote].presence or abort "Provide the new quote text as the second argument." + + testimonial = find_testimonial!(username) + puts "Was: #{testimonial.quote}" + + testimonial.system_generated = true + unless testimonial.update(quote: new_quote) + abort "Rejected: #{testimonial.errors.full_messages.to_sentence}" + end + + puts "Now: #{testimonial.quote}" + puts "Regenerating AI fields..." + testimonial.update_columns(ai_attempts: 0, ai_feedback: nil, reject_reason: nil) + testimonial.generate_ai_fields! + testimonial.reload + + puts " heading: #{testimonial.heading}" + puts " subheading: #{testimonial.subheading}" + puts " body: #{testimonial.body_text}" + puts " published: #{testimonial.published?}" + end + + def find_testimonial!(username) + user = User.find_by(username: username) or abort "No user named #{username}." + user.testimonial or abort "#{username} has no testimonial." + end end diff --git a/test/controllers/testimonials_controller_test.rb b/test/controllers/testimonials_controller_test.rb index 526d5b4..cfc40fa 100644 --- a/test/controllers/testimonials_controller_test.rb +++ b/test/controllers/testimonials_controller_test.rb @@ -51,4 +51,22 @@ class TestimonialsControllerTest < ActionDispatch::IntegrationTest assert_redirected_to user_path(user) end + + test "an over-long quote is rejected with the full text preserved, never trimmed" do + sign_in users(:user_no_testimonial) + long = "I love Ruby because " + ("it reads like plain English and gets out of my way. " * 12) + + assert_no_difference -> { Testimonial.count } do + post testimonial_path, params: { testimonial: { quote: long } } + end + end + + test "a self-promotional quote is refused" do + sign_in users(:user_no_testimonial) + promo = "I love Ruby because it lets me ship fast for my clients every single week of the year without fail. Visit rubygrowthlabs.com" + + assert_no_difference -> { Testimonial.count } do + post testimonial_path, params: { testimonial: { quote: promo } } + end + end end diff --git a/test/models/concerns/testimonial/ai_translatable_test.rb b/test/models/concerns/testimonial/ai_translatable_test.rb new file mode 100644 index 0000000..5b075a5 --- /dev/null +++ b/test/models/concerns/testimonial/ai_translatable_test.rb @@ -0,0 +1,40 @@ +require "test_helper" + +class Testimonial::AiTranslatableTest < ActiveSupport::TestCase + setup do + @testimonial = testimonials(:published) + end + + test "needs_translation? is true for an untranslated quote" do + assert @testimonial.needs_translation? + end + + test "needs_translation? is false once an original is stored" do + @testimonial.update_columns(quote_original: "Ha trasformato il mio modo di sviluppare", quote_language: "it") + assert_not @testimonial.reload.needs_translation? + assert @testimonial.translated? + end + + test "needs_translation? is false for a blank quote" do + @testimonial.update_columns(quote: nil) + assert_not @testimonial.reload.needs_translation? + end + + test "a translated quote longer than the authoring cap is stored in full" do + long = "E" * 900 + @testimonial.system_generated = true + @testimonial.quote = long + + assert @testimonial.valid?, @testimonial.errors.full_messages.to_sentence + @testimonial.save! + assert_equal 900, @testimonial.reload.quote.length + end + + test "a user-submitted quote over the cap is rejected, not trimmed" do + t = Testimonial.new(user: users(:user_no_testimonial), quote: "R" * 400) + + assert_not t.valid? + assert t.errors[:quote].any? { |e| e.include?("too long") } + assert_equal 400, t.quote.length, "the quote must never be silently shortened" + end +end diff --git a/test/models/concerns/testimonial/screenable_test.rb b/test/models/concerns/testimonial/screenable_test.rb new file mode 100644 index 0000000..3ce61e8 --- /dev/null +++ b/test/models/concerns/testimonial/screenable_test.rb @@ -0,0 +1,67 @@ +require "test_helper" + +class Testimonial::ScreenableTest < ActiveSupport::TestCase + # A quote long enough to pass the 140-char minimum, so screening is what decides. + def build(quote) + Testimonial.new(user: users(:user_no_testimonial), quote: quote) + end + + test "flags a quote containing a bare URL" do + t = build("I love Ruby because it lets me ship fast and the community is wonderful to be around every single day of the week. Read my blog here: https://medium.com/@someone") + assert t.self_promotional? + assert_match(/link/i, t.screening_feedback) + end + + test "flags a quote containing a www address" do + t = build("I love Ruby because it is elegant and expressive and has been my favourite language for more than a decade now, truly. Visit www.example.com for more") + assert t.self_promotional? + end + + test "flags a quote containing a bare domain" do + t = build("I love Ruby because it is elegant and expressive and has been my favourite language for more than a decade now, truly great. Check rubygrowthlabs.com") + assert t.self_promotional? + end + + test "flags a quote containing an email address" do + t = build("I love Ruby because it is elegant and expressive and has been my favourite language for more than a decade now, truly. Email me at hello@example.org") + assert t.self_promotional? + end + + test "flags a quote with a hire-me call to action" do + t = build("Ruby is the best language for AI-powered development and we ship at tremendous speed using agents on the majestic monolith. I help founders build Rails apps fast.") + assert t.self_promotional? + assert_match(/pitch/i, t.screening_feedback) + end + + test "flags a quote that is a services pitch" do + t = build("Ruby and Rails are a wonderful combination that I have relied on for years to deliver real value to clients quickly. Contact me if you need help with yours!") + assert t.self_promotional? + end + + test "does not flag an ordinary heartfelt testimonial" do + t = build("I love Ruby because it makes programming feel human. The language reads almost like plain English, which lets me focus on solving real problems instead of fighting syntax.") + assert_not t.self_promotional? + assert_nil t.screening_feedback + end + + test "does not flag a quote that merely mentions Rails and gems" do + t = build("I love Ruby because the ecosystem has already solved the hard problems for you. From gems to standard libraries, the tools are mature and concise, which lets me prototype rapidly.") + assert_not t.self_promotional? + end + + test "does not flag a quote mentioning version numbers or decimals" do + t = build("I have loved Ruby since version 1.8 and every release since has made the language better without ever losing the warmth and clarity that drew me to it in the first place.") + assert_not t.self_promotional? + end + + test "does not flag a quote using the word visit innocently" do + t = build("Every time I visit an old Ruby codebase of mine I can still read it perfectly, which says everything about how well this language ages over the years and years.") + assert_not t.self_promotional? + end + + test "screening runs on validation and blocks a promotional quote" do + t = build("I love Ruby because it is elegant and expressive and has been my favourite language for more than a decade now, truly. Visit rubygrowthlabs.com") + assert_not t.valid? + assert t.errors[:quote].any? + end +end diff --git a/test/models/concerns/user/github_syncable_test.rb b/test/models/concerns/user/github_syncable_test.rb index 1609d90..377e851 100644 --- a/test/models/concerns/user/github_syncable_test.rb +++ b/test/models/concerns/user/github_syncable_test.rb @@ -48,4 +48,51 @@ class User::GithubSyncableTest < ActiveSupport::TestCase assert_equal 1, result[:failed] assert_match(/EOFError/, result[:errors].first.to_s) end + + test "batch_sync_github_data! preserves existing bio when GitHub returns nil" do + @user.update_columns(bio: "Loves Ruby since 2005") + + stub_graphql_user(bio: nil) + + result = User.batch_sync_github_data!([ @user ], api_token: "token") + + assert_equal 1, result[:updated], result[:errors].inspect + assert_equal "Loves Ruby since 2005", @user.reload.bio + end + + test "batch_sync_github_data! preserves existing bio when GitHub returns empty string" do + @user.update_columns(bio: "Loves Ruby since 2005") + + stub_graphql_user(bio: "") + + result = User.batch_sync_github_data!([ @user ], api_token: "token") + + assert_equal 1, result[:updated], result[:errors].inspect + assert_equal "Loves Ruby since 2005", @user.reload.bio + end + + test "batch_sync_github_data! updates bio when GitHub returns a non-blank value" do + @user.update_columns(bio: "Old bio") + + stub_graphql_user(bio: "Fresh bio from GitHub") + + result = User.batch_sync_github_data!([ @user ], api_token: "token") + + assert_equal 1, result[:updated], result[:errors].inspect + assert_equal "Fresh bio from GitHub", @user.reload.bio + end + + private + + def stub_graphql_user(bio:) + stub_request(:post, User::GithubSyncable::GITHUB_GRAPHQL_ENDPOINT).to_return( + status: 200, + body: { + data: { + user_0: { login: "octocat", name: "The Octocat", email: nil, bio: bio, company: nil, websiteUrl: nil, twitterUsername: nil, location: nil, avatarUrl: "https://example.com/a.png" }, + repos_0: { nodes: [] } + } + }.to_json + ) + end end diff --git a/vendor/icc/ISOcoated_v2_eci.icc b/vendor/icc/ISOcoated_v2_eci.icc new file mode 100755 index 0000000..dceb393 Binary files /dev/null and b/vendor/icc/ISOcoated_v2_eci.icc differ diff --git a/vendor/icc/PSOcoated_v3.icc b/vendor/icc/PSOcoated_v3.icc new file mode 100755 index 0000000..657da7c Binary files /dev/null and b/vendor/icc/PSOcoated_v3.icc differ