diff options
Diffstat (limited to 'guides')
31 files changed, 409 insertions, 358 deletions
diff --git a/guides/Rakefile b/guides/Rakefile index 00577377d7..353966fc55 100644 --- a/guides/Rakefile +++ b/guides/Rakefile @@ -1,7 +1,7 @@ namespace :guides do desc 'Generate guides (for authors), use ONLY=foo to process just "foo.md"' - task :generate => 'generate:html' + task generate: "generate:html" namespace :generate do @@ -16,11 +16,11 @@ namespace :guides do unless `kindlerb -v 2> /dev/null` =~ /kindlerb 0.1.1/ abort "Please `gem install kindlerb` and make sure you have `kindlegen` in your PATH" end - unless `convert` =~ /convert/ + unless `convert` =~ /convert/ abort "Please install ImageMagick`" end - ENV['KINDLE'] = '1' - Rake::Task['guides:generate:html'].invoke + ENV["KINDLE"] = "1" + Rake::Task["guides:generate:html"].invoke end end @@ -76,4 +76,4 @@ Examples: end end -task :default => 'guides:help' +task default: "guides:help" diff --git a/guides/bug_report_templates/action_controller_gem.rb b/guides/bug_report_templates/action_controller_gem.rb index e22c9327a4..960d269d90 100644 --- a/guides/bug_report_templates/action_controller_gem.rb +++ b/guides/bug_report_templates/action_controller_gem.rb @@ -1,30 +1,30 @@ begin - require 'bundler/inline' + require "bundler/inline" rescue LoadError => e - $stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler' + $stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler" raise e end gemfile(true) do - source 'https://rubygems.org' + source "https://rubygems.org" # Activate the gem you are reporting the issue against. - gem 'rails', '5.0.0' + gem "rails", "5.0.0" end -require 'rack/test' -require 'action_controller/railtie' +require "rack/test" +require "action_controller/railtie" class TestApp < Rails::Application config.root = File.dirname(__FILE__) - config.session_store :cookie_store, key: 'cookie_store_key' - secrets.secret_token = 'secret_token' - secrets.secret_key_base = 'secret_key_base' + config.session_store :cookie_store, key: "cookie_store_key" + secrets.secret_token = "secret_token" + secrets.secret_key_base = "secret_key_base" config.logger = Logger.new($stdout) Rails.logger = config.logger routes.draw do - get '/' => 'test#index' + get "/" => "test#index" end end @@ -32,11 +32,11 @@ class TestController < ActionController::Base include Rails.application.routes.url_helpers def index - render plain: 'Home' + render plain: "Home" end end -require 'minitest/autorun' +require "minitest/autorun" # Ensure backward compatibility with Minitest 4 Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test) @@ -45,7 +45,7 @@ class BugTest < Minitest::Test include Rack::Test::Methods def test_returns_success - get '/' + get "/" assert last_response.ok? end diff --git a/guides/bug_report_templates/action_controller_master.rb b/guides/bug_report_templates/action_controller_master.rb index 8322707495..cd0a3be85c 100644 --- a/guides/bug_report_templates/action_controller_master.rb +++ b/guides/bug_report_templates/action_controller_master.rb @@ -1,28 +1,28 @@ begin - require 'bundler/inline' + require "bundler/inline" rescue LoadError => e - $stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler' + $stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler" raise e end gemfile(true) do - source 'https://rubygems.org' - gem 'rails', github: 'rails/rails' + source "https://rubygems.org" + gem "rails", github: "rails/rails" end -require 'action_controller/railtie' +require "action_controller/railtie" class TestApp < Rails::Application config.root = File.dirname(__FILE__) - config.session_store :cookie_store, key: 'cookie_store_key' - secrets.secret_token = 'secret_token' - secrets.secret_key_base = 'secret_key_base' + config.session_store :cookie_store, key: "cookie_store_key" + secrets.secret_token = "secret_token" + secrets.secret_key_base = "secret_key_base" config.logger = Logger.new($stdout) Rails.logger = config.logger routes.draw do - get '/' => 'test#index' + get "/" => "test#index" end end @@ -30,18 +30,18 @@ class TestController < ActionController::Base include Rails.application.routes.url_helpers def index - render plain: 'Home' + render plain: "Home" end end -require 'minitest/autorun' -require 'rack/test' +require "minitest/autorun" +require "rack/test" class BugTest < Minitest::Test include Rack::Test::Methods def test_returns_success - get '/' + get "/" assert last_response.ok? end diff --git a/guides/bug_report_templates/active_record_gem.rb b/guides/bug_report_templates/active_record_gem.rb index 46fd2f1aae..e18302fe65 100644 --- a/guides/bug_report_templates/active_record_gem.rb +++ b/guides/bug_report_templates/active_record_gem.rb @@ -1,26 +1,26 @@ begin - require 'bundler/inline' + require "bundler/inline" rescue LoadError => e - $stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler' + $stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler" raise e end gemfile(true) do - source 'https://rubygems.org' + source "https://rubygems.org" # Activate the gem you are reporting the issue against. - gem 'activerecord', '5.0.0' - gem 'sqlite3' + gem "activerecord", "5.0.0" + gem "sqlite3" end -require 'active_record' -require 'minitest/autorun' -require 'logger' +require "active_record" +require "minitest/autorun" +require "logger" # Ensure backward compatibility with Minitest 4 Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test) # This connection will do for database-independent bug reports. -ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:') +ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") ActiveRecord::Base.logger = Logger.new(STDOUT) ActiveRecord::Schema.define do diff --git a/guides/bug_report_templates/active_record_master.rb b/guides/bug_report_templates/active_record_master.rb index 6fd401bd50..7265a671b0 100644 --- a/guides/bug_report_templates/active_record_master.rb +++ b/guides/bug_report_templates/active_record_master.rb @@ -1,22 +1,22 @@ begin - require 'bundler/inline' + require "bundler/inline" rescue LoadError => e - $stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler' + $stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler" raise e end gemfile(true) do - source 'https://rubygems.org' - gem 'rails', github: 'rails/rails' - gem 'sqlite3' + source "https://rubygems.org" + gem "rails", github: "rails/rails" + gem "sqlite3" end -require 'active_record' -require 'minitest/autorun' -require 'logger' +require "active_record" +require "minitest/autorun" +require "logger" # This connection will do for database-independent bug reports. -ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:') +ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") ActiveRecord::Base.logger = Logger.new(STDOUT) ActiveRecord::Schema.define do diff --git a/guides/bug_report_templates/generic_gem.rb b/guides/bug_report_templates/generic_gem.rb index 2aaaf10615..a94848e25b 100644 --- a/guides/bug_report_templates/generic_gem.rb +++ b/guides/bug_report_templates/generic_gem.rb @@ -1,18 +1,18 @@ begin - require 'bundler/inline' + require "bundler/inline" rescue LoadError => e - $stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler' + $stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler" raise e end gemfile(true) do - source 'https://rubygems.org' + source "https://rubygems.org" # Activate the gem you are reporting the issue against. - gem 'activesupport', '5.0.0' + gem "activesupport", "5.0.0" end -require 'active_support/core_ext/object/blank' -require 'minitest/autorun' +require "active_support/core_ext/object/blank" +require "minitest/autorun" # Ensure backward compatibility with Minitest 4 Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test) diff --git a/guides/bug_report_templates/generic_master.rb b/guides/bug_report_templates/generic_master.rb index 70cf931f34..d3a7ae4ac4 100644 --- a/guides/bug_report_templates/generic_master.rb +++ b/guides/bug_report_templates/generic_master.rb @@ -1,18 +1,18 @@ begin - require 'bundler/inline' + require "bundler/inline" rescue LoadError => e - $stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler' + $stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler" raise e end gemfile(true) do - source 'https://rubygems.org' - gem 'rails', github: 'rails/rails' + source "https://rubygems.org" + gem "rails", github: "rails/rails" end -require 'active_support' -require 'active_support/core_ext/object/blank' -require 'minitest/autorun' +require "active_support" +require "active_support/core_ext/object/blank" +require "minitest/autorun" class BugTest < Minitest::Test def test_stuff diff --git a/guides/rails_guides.rb b/guides/rails_guides.rb index 367ed0b12e..557d23f78c 100644 --- a/guides/rails_guides.rb +++ b/guides/rails_guides.rb @@ -10,7 +10,7 @@ begin $:.unshift ap_lib if File.directory?(ap_lib) rescue LoadError # Guides generation from gems. - gem "actionpack", '>= 3.0' + gem "actionpack", ">= 3.0" end require "rails_guides/generator" diff --git a/guides/rails_guides/generator.rb b/guides/rails_guides/generator.rb index 48ac90fca4..39a57191eb 100644 --- a/guides/rails_guides/generator.rb +++ b/guides/rails_guides/generator.rb @@ -49,18 +49,18 @@ # # --------------------------------------------------------------------------- -require 'set' -require 'fileutils' +require "set" +require "fileutils" -require 'active_support/core_ext/string/output_safety' -require 'active_support/core_ext/object/blank' -require 'action_controller' -require 'action_view' +require "active_support/core_ext/string/output_safety" +require "active_support/core_ext/object/blank" +require "action_controller" +require "action_view" -require 'rails_guides/markdown' -require 'rails_guides/indexer' -require 'rails_guides/helpers' -require 'rails_guides/levenshtein' +require "rails_guides/markdown" +require "rails_guides/indexer" +require "rails_guides/helpers" +require "rails_guides/levenshtein" module RailsGuides class Generator @@ -81,12 +81,12 @@ module RailsGuides end def set_flags_from_environment - @edge = ENV['EDGE'] == '1' - @warnings = ENV['WARNINGS'] == '1' - @all = ENV['ALL'] == '1' - @kindle = ENV['KINDLE'] == '1' - @version = ENV['RAILS_VERSION'] || 'local' - @lang = ENV['GUIDES_LANGUAGE'] + @edge = ENV["EDGE"] == "1" + @warnings = ENV["WARNINGS"] == "1" + @all = ENV["ALL"] == "1" + @kindle = ENV["KINDLE"] == "1" + @version = ENV["RAILS_VERSION"] || "local" + @lang = ENV["GUIDES_LANGUAGE"] end def register_kindle_mime_types @@ -102,148 +102,148 @@ module RailsGuides private - def kindle? - @kindle - end + def kindle? + @kindle + end - def check_for_kindlegen - if `which kindlegen`.blank? - raise "Can't create a kindle version without `kindlegen`." + def check_for_kindlegen + if `which kindlegen`.blank? + raise "Can't create a kindle version without `kindlegen`." + end end - end - def generate_mobi - require 'rails_guides/kindle' - out = "#{output_dir}/kindlegen.out" - Kindle.generate(output_dir, mobi, out) - puts "(kindlegen log at #{out})." - end + def generate_mobi + require "rails_guides/kindle" + out = "#{output_dir}/kindlegen.out" + Kindle.generate(output_dir, mobi, out) + puts "(kindlegen log at #{out})." + end - def mobi - "ruby_on_rails_guides_#@version%s.mobi" % (@lang.present? ? ".#@lang" : '') - end + def mobi + "ruby_on_rails_guides_#@version%s.mobi" % (@lang.present? ? ".#@lang" : "") + end - def initialize_dirs(output) - @guides_dir = File.join(File.dirname(__FILE__), '..') - @source_dir = "#@guides_dir/source/#@lang" - @output_dir = if output - output - elsif kindle? - "#@guides_dir/output/kindle/#@lang" - else - "#@guides_dir/output/#@lang" - end.sub(%r</$>, '') - end + def initialize_dirs(output) + @guides_dir = File.join(File.dirname(__FILE__), "..") + @source_dir = "#@guides_dir/source/#@lang" + @output_dir = if output + output + elsif kindle? + "#@guides_dir/output/kindle/#@lang" + else + "#@guides_dir/output/#@lang" + end.sub(%r</$>, "") + end - def create_output_dir_if_needed - FileUtils.mkdir_p(output_dir) - end + def create_output_dir_if_needed + FileUtils.mkdir_p(output_dir) + end - def generate_guides - guides_to_generate.each do |guide| - output_file = output_file_for(guide) - generate_guide(guide, output_file) if generate?(guide, output_file) + def generate_guides + guides_to_generate.each do |guide| + output_file = output_file_for(guide) + generate_guide(guide, output_file) if generate?(guide, output_file) + end end - end - def guides_to_generate - guides = Dir.entries(source_dir).grep(GUIDES_RE) + def guides_to_generate + guides = Dir.entries(source_dir).grep(GUIDES_RE) - if kindle? - Dir.entries("#{source_dir}/kindle").grep(GUIDES_RE).map do |entry| - next if entry == 'KINDLE.md' - guides << "kindle/#{entry}" + if kindle? + Dir.entries("#{source_dir}/kindle").grep(GUIDES_RE).map do |entry| + next if entry == "KINDLE.md" + guides << "kindle/#{entry}" + end end + + ENV.key?("ONLY") ? select_only(guides) : guides end - ENV.key?('ONLY') ? select_only(guides) : guides - end + def select_only(guides) + prefixes = ENV["ONLY"].split(",").map(&:strip) + guides.select do |guide| + guide.start_with?("kindle".freeze, *prefixes) + end + end - def select_only(guides) - prefixes = ENV['ONLY'].split(",").map(&:strip) - guides.select do |guide| - guide.start_with?('kindle'.freeze, *prefixes) + def copy_assets + FileUtils.cp_r(Dir.glob("#{guides_dir}/assets/*"), output_dir) end - end - def copy_assets - FileUtils.cp_r(Dir.glob("#{guides_dir}/assets/*"), output_dir) - end + def output_file_for(guide) + if guide.end_with?(".md") + guide.sub(/md\z/, "html") + else + guide.sub(/\.erb\z/, "") + end + end - def output_file_for(guide) - if guide.end_with?('.md') - guide.sub(/md\z/, 'html') - else - guide.sub(/\.erb\z/, '') + def output_path_for(output_file) + File.join(output_dir, File.basename(output_file)) end - end - def output_path_for(output_file) - File.join(output_dir, File.basename(output_file)) - end + def generate?(source_file, output_file) + fin = File.join(source_dir, source_file) + fout = output_path_for(output_file) + all || !File.exist?(fout) || File.mtime(fout) < File.mtime(fin) + end - def generate?(source_file, output_file) - fin = File.join(source_dir, source_file) - fout = output_path_for(output_file) - all || !File.exist?(fout) || File.mtime(fout) < File.mtime(fin) - end + def generate_guide(guide, output_file) + output_path = output_path_for(output_file) + puts "Generating #{guide} as #{output_file}" + layout = kindle? ? "kindle/layout" : "layout" - def generate_guide(guide, output_file) - output_path = output_path_for(output_file) - puts "Generating #{guide} as #{output_file}" - layout = kindle? ? 'kindle/layout' : 'layout' + File.open(output_path, "w") do |f| + view = ActionView::Base.new(source_dir, edge: @edge, version: @version, mobi: "kindle/#{mobi}", lang: @lang) + view.extend(Helpers) - File.open(output_path, 'w') do |f| - view = ActionView::Base.new(source_dir, :edge => @edge, :version => @version, :mobi => "kindle/#{mobi}", :lang => @lang) - view.extend(Helpers) + if guide =~ /\.(\w+)\.erb$/ + # Generate the special pages like the home. + # Passing a template handler in the template name is deprecated. So pass the file name without the extension. + result = view.render(layout: layout, formats: [$1], file: $`) + else + body = File.read(File.join(source_dir, guide)) + result = RailsGuides::Markdown.new(view, layout).render(body) - if guide =~ /\.(\w+)\.erb$/ - # Generate the special pages like the home. - # Passing a template handler in the template name is deprecated. So pass the file name without the extension. - result = view.render(:layout => layout, :formats => [$1], :file => $`) - else - body = File.read(File.join(source_dir, guide)) - result = RailsGuides::Markdown.new(view, layout).render(body) + warn_about_broken_links(result) if @warnings + end - warn_about_broken_links(result) if @warnings + f.write(result) end - - f.write(result) end - end - def warn_about_broken_links(html) - anchors = extract_anchors(html) - check_fragment_identifiers(html, anchors) - end + def warn_about_broken_links(html) + anchors = extract_anchors(html) + check_fragment_identifiers(html, anchors) + end - def extract_anchors(html) - # Markdown generates headers with IDs computed from titles. - anchors = Set.new - html.scan(/<h\d\s+id="([^"]+)/).flatten.each do |anchor| - if anchors.member?(anchor) - puts "*** DUPLICATE ID: #{anchor}, please make sure that there're no headings with the same name at the same level." - else - anchors << anchor + def extract_anchors(html) + # Markdown generates headers with IDs computed from titles. + anchors = Set.new + html.scan(/<h\d\s+id="([^"]+)/).flatten.each do |anchor| + if anchors.member?(anchor) + puts "*** DUPLICATE ID: #{anchor}, please make sure that there're no headings with the same name at the same level." + else + anchors << anchor + end end - end - # Footnotes. - anchors += Set.new(html.scan(/<p\s+class="footnote"\s+id="([^"]+)/).flatten) - anchors += Set.new(html.scan(/<sup\s+class="footnote"\s+id="([^"]+)/).flatten) - return anchors - end + # Footnotes. + anchors += Set.new(html.scan(/<p\s+class="footnote"\s+id="([^"]+)/).flatten) + anchors += Set.new(html.scan(/<sup\s+class="footnote"\s+id="([^"]+)/).flatten) + return anchors + end - def check_fragment_identifiers(html, anchors) - html.scan(/<a\s+href="#([^"]+)/).flatten.each do |fragment_identifier| - next if fragment_identifier == 'mainCol' # in layout, jumps to some DIV - unless anchors.member?(fragment_identifier) - guess = anchors.min { |a, b| - Levenshtein.distance(fragment_identifier, a) <=> Levenshtein.distance(fragment_identifier, b) - } - puts "*** BROKEN LINK: ##{fragment_identifier}, perhaps you meant ##{guess}." + def check_fragment_identifiers(html, anchors) + html.scan(/<a\s+href="#([^"]+)/).flatten.each do |fragment_identifier| + next if fragment_identifier == "mainCol" # in layout, jumps to some DIV + unless anchors.member?(fragment_identifier) + guess = anchors.min { |a, b| + Levenshtein.distance(fragment_identifier, a) <=> Levenshtein.distance(fragment_identifier, b) + } + puts "*** BROKEN LINK: ##{fragment_identifier}, perhaps you meant ##{guess}." + end end end - end end end diff --git a/guides/rails_guides/helpers.rb b/guides/rails_guides/helpers.rb index 5bf73da16c..888b51b1ef 100644 --- a/guides/rails_guides/helpers.rb +++ b/guides/rails_guides/helpers.rb @@ -1,13 +1,13 @@ -require 'yaml' +require "yaml" module RailsGuides module Helpers def guide(name, url, options = {}, &block) - link = content_tag(:a, :href => url) { name } + link = content_tag(:a, href: url) { name } result = content_tag(:dt, link) if options[:work_in_progress] - result << content_tag(:dd, 'Work in progress', :class => 'work-in-progress') + result << content_tag(:dd, "Work in progress", class: "work-in-progress") end result << content_tag(:dd, capture(&block)) @@ -19,30 +19,30 @@ module RailsGuides end def documents_flat - documents_by_section.flat_map {|section| section['documents']} + documents_by_section.flat_map { |section| section["documents"] } end def finished_documents(documents) - documents.reject { |document| document['work_in_progress'] } + documents.reject { |document| document["work_in_progress"] } end def docs_for_menu(position=nil) if position.nil? documents_by_section - elsif position == 'L' + elsif position == "L" documents_by_section.to(3) else documents_by_section.from(4) end end - def author(name, nick, image = 'credits_pic_blank.gif', &block) + def author(name, nick, image = "credits_pic_blank.gif", &block) image = "images/#{image}" - result = tag(:img, :src => image, :class => 'left pic', :alt => name, :width => 91, :height => 91) + result = tag(:img, src: image, class: "left pic", alt: name, width: 91, height: 91) result << content_tag(:h3, name) result << content_tag(:p, capture(&block)) - content_tag(:div, result, :class => 'clearfix', :id => nick) + content_tag(:div, result, class: "clearfix", id: nick) end def code(&block) diff --git a/guides/rails_guides/indexer.rb b/guides/rails_guides/indexer.rb index 89fbccbb1d..56df6a5842 100644 --- a/guides/rails_guides/indexer.rb +++ b/guides/rails_guides/indexer.rb @@ -1,5 +1,5 @@ -require 'active_support/core_ext/object/blank' -require 'active_support/core_ext/string/inflections' +require "active_support/core_ext/object/blank" +require "active_support/core_ext/string/inflections" module RailsGuides class Indexer @@ -17,52 +17,52 @@ module RailsGuides private - def process(string, current_level=3, counters=[1]) - s = StringScanner.new(string) + def process(string, current_level=3, counters=[1]) + s = StringScanner.new(string) - level_hash = {} + level_hash = {} - while !s.eos? - re = %r{^h(\d)(?:\((#.*?)\))?\s*\.\s*(.*)$} - s.match?(re) - if matched = s.matched - matched =~ re - level, idx, title = $1.to_i, $2, $3.strip + while !s.eos? + re = %r{^h(\d)(?:\((#.*?)\))?\s*\.\s*(.*)$} + s.match?(re) + if matched = s.matched + matched =~ re + level, idx, title = $1.to_i, $2, $3.strip - if level < current_level - # This is needed. Go figure. - return level_hash - elsif level == current_level - index = counters.join(".") - idx ||= '#' + title_to_idx(title) + if level < current_level + # This is needed. Go figure. + return level_hash + elsif level == current_level + index = counters.join(".") + idx ||= "#" + title_to_idx(title) - raise "Parsing Fail" unless @result.sub!(matched, "h#{level}(#{idx}). #{index} #{title}") + raise "Parsing Fail" unless @result.sub!(matched, "h#{level}(#{idx}). #{index} #{title}") - key = { - :title => title, - :id => idx - } - # Recurse - counters << 1 - level_hash[key] = process(s.post_match, current_level + 1, counters) - counters.pop + key = { + title: title, + id: idx + } + # Recurse + counters << 1 + level_hash[key] = process(s.post_match, current_level + 1, counters) + counters.pop - # Increment the current level - last = counters.pop - counters << last + 1 + # Increment the current level + last = counters.pop + counters << last + 1 + end end + s.getch end - s.getch + level_hash end - level_hash - end - def title_to_idx(title) - idx = title.strip.parameterize.sub(/^\d+/, '') - if warnings && idx.blank? - puts "BLANK ID: please put an explicit ID for section #{title}, as in h5(#my-id)" + def title_to_idx(title) + idx = title.strip.parameterize.sub(/^\d+/, "") + if warnings && idx.blank? + puts "BLANK ID: please put an explicit ID for section #{title}, as in h5(#my-id)" + end + idx end - idx - end end end diff --git a/guides/rails_guides/kindle.rb b/guides/rails_guides/kindle.rb index 081afcb09f..6fb8183cb1 100644 --- a/guides/rails_guides/kindle.rb +++ b/guides/rails_guides/kindle.rb @@ -1,26 +1,26 @@ #!/usr/bin/env ruby -unless `which kindlerb` +unless `which kindlerb` abort "Please gem install kindlerb" end -require 'nokogiri' -require 'fileutils' -require 'yaml' -require 'date' +require "nokogiri" +require "fileutils" +require "yaml" +require "date" module Kindle extend self def generate(output_dir, mobi_outfile, logfile) output_dir = File.absolute_path(output_dir) - Dir.chdir output_dir do + Dir.chdir output_dir do puts "=> Using output dir: #{output_dir}" puts "=> Arranging html pages in document order" toc = File.read("toc.ncx") - doc = Nokogiri::XML(toc).xpath("//ncx:content", 'ncx' => "http://www.daisy.org/z3986/2005/ncx/") - html_pages = doc.select {|c| c[:src]}.map {|c| c[:src]}.uniq - + doc = Nokogiri::XML(toc).xpath("//ncx:content", "ncx" => "http://www.daisy.org/z3986/2005/ncx/") + html_pages = doc.select { |c| c[:src] }.map { |c| c[:src] }.uniq + generate_front_matter(html_pages) generate_sections(html_pages) @@ -37,26 +37,26 @@ module Kindle def generate_front_matter(html_pages) frontmatter = [] - html_pages.delete_if {|x| + html_pages.delete_if { |x| if x =~ /(toc|welcome|credits|copyright).html/ frontmatter << x unless x =~ /toc/ true end } - html = frontmatter.map {|x| + html = frontmatter.map { |x| Nokogiri::HTML(File.open(x)).at("body").inner_html }.join("\n") fdoc = Nokogiri::HTML(html) fdoc.search("h3").each do |h3| - h3.name = 'h4' + h3.name = "h4" end - fdoc.search("h2").each do |h2| - h2.name = 'h3' - h2['id'] = h2.inner_text.gsub(/\s/, '-') + fdoc.search("h2").each do |h2| + h2.name = "h3" + h2["id"] = h2.inner_text.gsub(/\s/, "-") end add_head_section fdoc, "Front Matter" - File.open("frontmatter.html",'w') {|f| f.puts fdoc.to_html} + File.open("frontmatter.html","w") { |f| f.puts fdoc.to_html } html_pages.unshift "frontmatter.html" end @@ -65,20 +65,20 @@ module Kindle html_pages.each_with_index do |page, section_idx| FileUtils::mkdir_p("sections/%03d" % section_idx) doc = Nokogiri::HTML(File.open(page)) - title = doc.at("title").inner_text.gsub("Ruby on Rails Guides: ", '') - title = page.capitalize.gsub('.html', '') if title.strip == '' - File.open("sections/%03d/_section.txt" % section_idx, 'w') {|f| f.puts title} + title = doc.at("title").inner_text.gsub("Ruby on Rails Guides: ", "") + title = page.capitalize.gsub(".html", "") if title.strip == "" + File.open("sections/%03d/_section.txt" % section_idx, "w") { |f| f.puts title } doc.xpath("//h3[@id]").each_with_index do |h3,item_idx| subsection = h3.inner_text - content = h3.xpath("./following-sibling::*").take_while {|x| x.name != "h3"}.map(&:to_html) + content = h3.xpath("./following-sibling::*").take_while { |x| x.name != "h3" }.map(&:to_html) item = Nokogiri::HTML(h3.to_html + content.join("\n")) - item_path = "sections/%03d/%03d.html" % [section_idx, item_idx] + item_path = "sections/%03d/%03d.html" % [section_idx, item_idx] add_head_section(item, subsection) item.search("img").each do |img| - img['src'] = "#{Dir.pwd}/#{img['src']}" + img["src"] = "#{Dir.pwd}/#{img['src']}" end - item.xpath("//li/p").each {|p| p.swap(p.children); p.remove} - File.open(item_path, 'w') {|f| f.puts item.to_html} + item.xpath("//li/p").each { |p| p.swap(p.children); p.remove } + File.open(item_path, "w") { |f| f.puts item.to_html } end end end @@ -87,21 +87,21 @@ module Kindle puts "=> Generating _document.yml" x = Nokogiri::XML(File.open("rails_guides.opf")).remove_namespaces! cover_jpg = "#{Dir.pwd}/images/rails_guides_kindle_cover.jpg" - cover_gif = cover_jpg.sub(/jpg$/, 'gif') + cover_gif = cover_jpg.sub(/jpg$/, "gif") puts `convert #{cover_jpg} #{cover_gif}` document = { - 'doc_uuid' => x.at("package")['unique-identifier'], - 'title' => x.at("title").inner_text.gsub(/\(.*$/, " v2"), - 'publisher' => x.at("publisher").inner_text, - 'author' => x.at("creator").inner_text, - 'subject' => x.at("subject").inner_text, - 'date' => x.at("date").inner_text, - 'cover' => cover_gif, - 'masthead' => nil, - 'mobi_outfile' => mobi_outfile + "doc_uuid" => x.at("package")["unique-identifier"], + "title" => x.at("title").inner_text.gsub(/\(.*$/, " v2"), + "publisher" => x.at("publisher").inner_text, + "author" => x.at("creator").inner_text, + "subject" => x.at("subject").inner_text, + "date" => x.at("date").inner_text, + "cover" => cover_gif, + "masthead" => nil, + "mobi_outfile" => mobi_outfile } puts document.to_yaml - File.open("_document.yml", 'w'){|f| f.puts document.to_yaml} + File.open("_document.yml", "w") { |f| f.puts document.to_yaml } end def add_head_section(doc, title) @@ -110,9 +110,9 @@ module Kindle title_node.content = title title_node.parent = head css = Nokogiri::XML::Node.new "link", doc - css['rel'] = 'stylesheet' - css['type'] = 'text/css' - css['href'] = "#{Dir.pwd}/stylesheets/kindle.css" + css["rel"] = "stylesheet" + css["type"] = "text/css" + css["href"] = "#{Dir.pwd}/stylesheets/kindle.css" css.parent = head doc.at("body").before head end diff --git a/guides/rails_guides/levenshtein.rb b/guides/rails_guides/levenshtein.rb index 049f633258..a3e7620444 100644 --- a/guides/rails_guides/levenshtein.rb +++ b/guides/rails_guides/levenshtein.rb @@ -2,7 +2,7 @@ module RailsGuides module Levenshtein # This code is based directly on the Text gem implementation # Returns a value representing the "cost" of transforming str1 into str2 - def self.distance str1, str2 + def self.distance(str1, str2) s = str1 t = str2 n = s.length diff --git a/guides/rails_guides/markdown.rb b/guides/rails_guides/markdown.rb index 69c7cd5136..33563d669c 100644 --- a/guides/rails_guides/markdown.rb +++ b/guides/rails_guides/markdown.rb @@ -1,6 +1,6 @@ -require 'redcarpet' -require 'nokogiri' -require 'rails_guides/markdown/renderer' +require "redcarpet" +require "nokogiri" +require "rails_guides/markdown/renderer" module RailsGuides class Markdown @@ -8,7 +8,7 @@ module RailsGuides @view = view @layout = layout @index_counter = Hash.new(0) - @raw_header = '' + @raw_header = "" @node_ids = {} end @@ -47,21 +47,20 @@ module RailsGuides def dom_id_text(text) escaped_chars = Regexp.escape('\\/`*_{}[]()#+-.!:,;|&<>^~=\'"') - text.downcase.gsub(/\?/, '-questionmark') - .gsub(/!/, '-bang') - .gsub(/[#{escaped_chars}]+/, ' ').strip - .gsub(/\s+/, '-') + text.downcase.gsub(/\?/, "-questionmark") + .gsub(/!/, "-bang") + .gsub(/[#{escaped_chars}]+/, " ").strip + .gsub(/\s+/, "-") end def engine - @engine ||= Redcarpet::Markdown.new(Renderer, { + @engine ||= Redcarpet::Markdown.new(Renderer, no_intra_emphasis: true, fenced_code_blocks: true, autolink: true, strikethrough: true, superscript: true, - tables: true - }) + tables: true) end def extract_raw_header_and_body @@ -87,15 +86,15 @@ module RailsGuides doc.children.each do |node| if node.name =~ /^h[3-6]$/ case node.name - when 'h3' + when "h3" hierarchy = [node] @headings_for_index << [1, node, node.inner_html] - when 'h4' + when "h4" hierarchy = hierarchy[0, 1] + [node] @headings_for_index << [2, node, node.inner_html] - when 'h5' + when "h5" hierarchy = hierarchy[0, 2] + [node] - when 'h6' + when "h6" hierarchy = hierarchy[0, 3] + [node] end @@ -109,7 +108,7 @@ module RailsGuides def generate_index if @headings_for_index.present? - raw_index = '' + raw_index = "" @headings_for_index.each do |level, node, label| if level == 1 raw_index += "1. [#{label}](##{node[:id]})\n" @@ -119,7 +118,7 @@ module RailsGuides end @index = Nokogiri::HTML.fragment(engine.render(raw_index)).tap do |doc| - doc.at('ol')[:class] = 'chapters' + doc.at("ol")[:class] = "chapters" end.to_html @index = <<-INDEX.html_safe @@ -159,7 +158,7 @@ module RailsGuides @view.content_for(:header_section) { @header } @view.content_for(:page_title) { @title } @view.content_for(:index_section) { @index } - @view.render(:layout => @layout, :text => @body) + @view.render(layout: @layout, text: @body) end end end diff --git a/guides/rails_guides/markdown/renderer.rb b/guides/rails_guides/markdown/renderer.rb index 73ca600361..4ff76c519b 100644 --- a/guides/rails_guides/markdown/renderer.rb +++ b/guides/rails_guides/markdown/renderer.rb @@ -25,7 +25,7 @@ HTML def paragraph(text) if text =~ /^(TIP|IMPORTANT|CAUTION|WARNING|NOTE|INFO|TODO)[.:]/ convert_notes(text) - elsif text.include?('DO NOT READ THIS FILE ON GITHUB') + elsif text.include?("DO NOT READ THIS FILE ON GITHUB") elsif text =~ /^\[<sup>(\d+)\]:<\/sup> (.+)$/ linkback = %(<a href="#footnote-#{$1}-ref"><sup>#{$1}</sup></a>) %(<p class="footnote" id="footnote-#{$1}">#{linkback} #{$2}</p>) @@ -46,14 +46,14 @@ HTML def brush_for(code_type) case code_type - when 'ruby', 'sql', 'plain' - code_type - when 'erb', 'html+erb' - 'ruby; html-script: true' - when 'html' - 'xml' # HTML is understood, but there are .xml rules in the CSS + when "ruby", "sql", "plain" + code_type + when "erb", "html+erb" + "ruby; html-script: true" + when "html" + "xml" # HTML is understood, but there are .xml rules in the CSS else - 'plain' + "plain" end end @@ -68,10 +68,10 @@ HTML # asterisk. body.gsub(/^(TIP|IMPORTANT|CAUTION|WARNING|NOTE|INFO|TODO)[.:](.*?)(\n(?=\n)|\Z)/m) do css_class = case $1 - when 'CAUTION', 'IMPORTANT' - 'warning' - when 'TIP' - 'info' + when "CAUTION", "IMPORTANT" + "warning" + when "TIP" + "info" else $1.downcase end diff --git a/guides/source/2_3_release_notes.md b/guides/source/2_3_release_notes.md index 06761b67bb..6976848e95 100644 --- a/guides/source/2_3_release_notes.md +++ b/guides/source/2_3_release_notes.md @@ -54,7 +54,7 @@ Documentation The [Ruby on Rails guides](http://guides.rubyonrails.org/) project has published several additional guides for Rails 2.3. In addition, a [separate site](http://edgeguides.rubyonrails.org/) maintains updated copies of the Guides for Edge Rails. Other documentation efforts include a relaunch of the [Rails wiki](http://newwiki.rubyonrails.org/) and early planning for a Rails Book. -* More Information: [Rails Documentation Projects](http://weblog.rubyonrails.org/2009/1/15/rails-documentation-projects.) +* More Information: [Rails Documentation Projects](http://weblog.rubyonrails.org/2009/1/15/rails-documentation-projects) Ruby 1.9.1 Support ------------------ diff --git a/guides/source/3_0_release_notes.md b/guides/source/3_0_release_notes.md index 49d37ba489..517b38be07 100644 --- a/guides/source/3_0_release_notes.md +++ b/guides/source/3_0_release_notes.md @@ -155,7 +155,7 @@ Documentation The documentation in the Rails tree is being updated with all the API changes, additionally, the [Rails Edge Guides](http://edgeguides.rubyonrails.org/) are being updated one by one to reflect the changes in Rails 3.0. The guides at [guides.rubyonrails.org](http://guides.rubyonrails.org/) however will continue to contain only the stable version of Rails (at this point, version 2.3.5, until 3.0 is released). -More Information: - [Rails Documentation Projects](http://weblog.rubyonrails.org/2009/1/15/rails-documentation-projects.) +More Information: - [Rails Documentation Projects](http://weblog.rubyonrails.org/2009/1/15/rails-documentation-projects) Internationalization diff --git a/guides/source/action_cable_overview.md b/guides/source/action_cable_overview.md index 02db86888c..118b0b52b2 100644 --- a/guides/source/action_cable_overview.md +++ b/guides/source/action_cable_overview.md @@ -242,10 +242,10 @@ WebNotificationsChannel.broadcast_to( The `WebNotificationsChannel.broadcast_to` call places a message in the current subscription adapter (Redis by default)'s pubsub queue under a separate broadcasting name for each user. For a user with an ID of 1, the broadcasting -name would be `web_notifications_1`. +name would be `web_notifications:1`. The channel has been instructed to stream everything that arrives at -`web_notifications_1` directly to the client by invoking the `received` +`web_notifications:1` directly to the client by invoking the `received` callback. ### Subscriptions @@ -313,7 +313,7 @@ App.cable.subscriptions.create { channel: "ChatChannel", room: "Best Room" }, ```ruby # Somewhere in your app this is called, perhaps # from a NewCommentJob. -ChatChannel.broadcast_to( +ActionCable.server.broadcast( "chat_#{room}", sent_by: 'Paul', body: 'This is a cool chat app.' diff --git a/guides/source/active_model_basics.md b/guides/source/active_model_basics.md index e834aeadb1..732e553c62 100644 --- a/guides/source/active_model_basics.md +++ b/guides/source/active_model_basics.md @@ -416,7 +416,6 @@ the Active Model API. ```ruby class Person include ActiveModel::Model - end ``` @@ -467,7 +466,7 @@ In order to make this work, the model must have an accessor named `password_dige The `has_secure_password` will add the following validations on the `password` accessor: 1. Password should be present. -2. Password should be equal to its confirmation. +2. Password should be equal to its confirmation (provided +password_confirmation+ is passed along). 3. The maximum length of a password is 72 (required by `bcrypt` on which ActiveModel::SecurePassword depends) #### Examples @@ -493,6 +492,10 @@ person.valid? # => false person.password = person.password_confirmation = 'a' * 100 person.valid? # => false +# When only password is supplied with no password_confirmation. +person.password = 'aditya' +person.valid? # => true + # When all validations are passed. person.password = person.password_confirmation = 'aditya' person.valid? # => true diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md index 8ffd0d033d..6f941d0e4e 100644 --- a/guides/source/active_record_querying.md +++ b/guides/source/active_record_querying.md @@ -1251,8 +1251,9 @@ articles, all the articles would still be loaded. By using `joins` (an INNER JOIN), the join conditions **must** match, otherwise no records will be returned. - - +NOTE: If an association is eager loaded as part of a join, any fields from a custom select clause will not present be on the loaded models. +This is because it is ambiguous whether they should appear on the parent record, or the child. + Scopes ------ diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md index 2737237c1a..665e97c470 100644 --- a/guides/source/active_record_validations.md +++ b/guides/source/active_record_validations.md @@ -290,7 +290,7 @@ You can also pass custom message via the `message` option. ```ruby class Person < ApplicationRecord - validates :terms_of_service, acceptance: true, message: 'must be abided' + validates :terms_of_service, acceptance: { message: 'must be abided' } end ``` diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md index 27478b21a0..aba4c6a97b 100644 --- a/guides/source/active_support_core_extensions.md +++ b/guides/source/active_support_core_extensions.md @@ -368,7 +368,7 @@ account.to_query('company[name]') so its output is ready to be used in a query string. -Arrays return the result of applying `to_query` to each element with `_key_[]` as key, and join the result with "&": +Arrays return the result of applying `to_query` to each element with `key[]` as key, and join the result with "&": ```ruby [3.4, -45.6].to_query('sample') diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md index cc84ecb216..a1b0029c47 100644 --- a/guides/source/caching_with_rails.md +++ b/guides/source/caching_with_rails.md @@ -512,6 +512,30 @@ class ProductsController < ApplicationController end ``` +Sometimes we want to cache response, for example a static page, that never gets +expired. To achieve this, we can use `http_cache_forever` helper and by doing +so browser and proxies will cache it indefinitely. + +By default cached responses will be private, cached only on the user's web +browser. To allow proxies to cache the response, set `public: true` to indicate +that they can serve the cached response to all users. + +Using this helper, `last_modified` header is set to `Time.new(2011, 1, 1).utc` +and `expires` header is set to a 100 years. + +WARNING: Use this method carefully as browser/proxy won't be able to invalidate +the cached response unless browser cache is forcefully cleared. + +```ruby +class HomeController < ApplicationController + def index + http_cache_forever(public: true) do + render + end + end +end +``` + ### Strong v/s Weak ETags Rails generates weak ETags by default. Weak ETags allow semantically equivalent diff --git a/guides/source/command_line.md b/guides/source/command_line.md index 42276bcb90..9d7ecce947 100644 --- a/guides/source/command_line.md +++ b/guides/source/command_line.md @@ -497,7 +497,13 @@ app/models/article.rb: NOTE. When using specific annotations and custom annotations, the annotation name (FIXME, BUG etc) is not displayed in the output lines. -By default, `rails notes` will look in the `app`, `config`, `db`, `lib` and `test` directories. If you would like to search other directories, you can provide them as a comma separated list in an environment variable `SOURCE_ANNOTATION_DIRECTORIES`. +By default, `rails notes` will look in the `app`, `config`, `db`, `lib` and `test` directories. If you would like to search other directories, you can configure them using `config.annotations.register_directories` option. + +```ruby +config.annotations.register_directories("spec", "vendor") +``` + +You can also provide them as a comma separated list in the environment variable `SOURCE_ANNOTATION_DIRECTORIES`. ```bash $ export SOURCE_ANNOTATION_DIRECTORIES='spec,vendor' diff --git a/guides/source/configuring.md b/guides/source/configuring.md index ed5975f31d..7239105b29 100644 --- a/guides/source/configuring.md +++ b/guides/source/configuring.md @@ -181,6 +181,8 @@ pipeline is enabled. It is set to `true` by default. * `config.assets.logger` accepts a logger conforming to the interface of Log4r or the default Ruby `Logger` class. Defaults to the same configured at `config.logger`. Setting `config.assets.logger` to `false` will turn off served assets logging. +* `config.assets.quiet` disables logging of assets requests. Set to `true` by default in `development.rb`. + ### Configuring Generators Rails allows you to alter what generators are used with the `config.generators` method. This method takes a block: @@ -400,6 +402,22 @@ The schema dumper adds one additional configuration option: * `config.action_controller.always_permitted_parameters` sets a list of whitelisted parameters that are permitted by default. The default values are `['controller', 'action']`. +* `config.action_controller.enable_fragment_cache_logging` determines whether to log fragment cache reads and writes in verbose format as follows: + + ``` + Read fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/d0bdf2974e1ef6d31685c3b392ad0b74 (0.6ms) + Rendered messages/_message.html.erb in 1.2 ms [cache hit] + Write fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/3b4e249ac9d168c617e32e84b99218b5 (1.1ms) + Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss] + ``` + + By default it is set to `false` which results in following output: + + ``` + Rendered messages/_message.html.erb in 1.2 ms [cache hit] + Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss] + ``` + ### Configuring Action Dispatch * `config.action_dispatch.session_store` sets the name of the store for session data. The default is `:cookie_store`; other valid options include `:active_record_store`, `:mem_cache_store` or the name of your own custom class. @@ -453,6 +471,8 @@ encrypted cookies salt value. Defaults to `'signed encrypted cookie'`. 'ActionDispatch::ParamsParser::ParseError' => :bad_request, 'ActionController::BadRequest' => :bad_request, 'ActionController::ParameterMissing' => :bad_request, + 'Rack::QueryParser::ParameterTypeError' => :bad_request, + 'Rack::QueryParser::InvalidParameterError' => :bad_request, 'ActiveRecord::RecordNotFound' => :not_found, 'ActiveRecord::StaleObjectError' => :conflict, 'ActiveRecord::RecordInvalid' => :unprocessable_entity, @@ -602,7 +622,7 @@ There are a few configuration options available in Active Support: * `config.active_support.time_precision` sets the precision of JSON encoded time values. Defaults to `3`. -* `ActiveSupport.halt_callback_chains_on_return_false` specifies whether Active Record and Active Model callback chains can be halted by returning `false` in a 'before' callback. When set to `false`, callback chains are halted only when explicitly done so with `throw(:abort)`. When set to `true`, callback chains are halted when a callback returns `false` (the previous behavior before Rails 5) and a deprecation warning is given. Defaults to `true` during the deprecation period. New Rails 5 apps generate an initializer file called `callback_terminator.rb` which sets the value to `false`. This file is *not* added when running `rails app:update`, so returning `false` will still work on older apps ported to Rails 5 and display a deprecation warning to prompt users to update their code. +* `ActiveSupport.halt_callback_chains_on_return_false` specifies whether Active Record and Active Model callback chains can be halted by returning `false` in a 'before' callback. When set to `false`, callback chains are halted only when explicitly done so with `throw(:abort)`. When set to `true`, callback chains are halted when a callback returns `false` (the previous behavior before Rails 5) and a deprecation warning is given. Defaults to `true` during the deprecation period. New Rails 5 apps generate an initializer file called `new_framework_defaults.rb` which sets the value to `false`. This file is *not* added when running `rails app:update`, so returning `false` will still work on older apps ported to Rails 5 and display a deprecation warning to prompt users to update their code. * `ActiveSupport::Logger.silencer` is set to `false` to disable the ability to silence logging in a block. The default is `true`. diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md index f0d0f9753a..df3003a6a8 100644 --- a/guides/source/debugging_rails_applications.md +++ b/guides/source/debugging_rails_applications.md @@ -946,16 +946,10 @@ development that will end your tailing of development.log. Have all information about your Rails app requests in the browser — in the Developer Tools panel. Provides insight to db/rendering/total times, parameter list, rendered views and more. +* [Pry](https://github.com/pry/pry) An IRB alternative and runtime developer console. References ---------- -* [ruby-debug Homepage](http://bashdb.sourceforge.net/ruby-debug/home-page.html) -* [debugger Homepage](https://github.com/cldwalker/debugger) * [byebug Homepage](https://github.com/deivid-rodriguez/byebug) * [web-console Homepage](https://github.com/rails/web-console) -* [Article: Debugging a Rails application with ruby-debug](http://www.sitepoint.com/debug-rails-app-ruby-debug/) -* [Ryan Bates' debugging ruby (revised) screencast](http://railscasts.com/episodes/54-debugging-ruby-revised) -* [Ryan Bates' stack trace screencast](http://railscasts.com/episodes/24-the-stack-trace) -* [Ryan Bates' logger screencast](http://railscasts.com/episodes/56-the-logger) -* [Debugging with ruby-debug](http://bashdb.sourceforge.net/ruby-debug.html) diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index 73dbb2bc40..0cb5d81042 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -68,7 +68,7 @@ The Rails philosophy includes two major guiding principles: again, our code is more maintainable, more extensible, and less buggy. * **Convention Over Configuration:** Rails has opinions about the best way to do many things in a web application, and defaults to this set of conventions, rather than - require that you specify every minutiae through endless configuration files. + require that you specify minutiae through endless configuration files. Creating a New Rails Project ---------------------------- @@ -148,6 +148,10 @@ This will create a Rails application called Blog in a `blog` directory and install the gem dependencies that are already mentioned in `Gemfile` using `bundle install`. +NOTE: If you're using Windows Subsystem for Linux then there are currently some +limitations on file system notifications that mean you should disable the `spring` +and `listen` gems which you can do by running `rails new blog --skip-spring --skip-listen`. + TIP: You can see all of the command line options that the Rails application builder accepts by running `rails new -h`. diff --git a/guides/source/i18n.md b/guides/source/i18n.md index 850f0def03..e623f8cf8a 100644 --- a/guides/source/i18n.md +++ b/guides/source/i18n.md @@ -866,7 +866,7 @@ This way you can provide special translations for various error messages at diff #### Error Message Interpolation -The translated model name, translated attribute name, and value are always available for interpolation. +The translated model name, translated attribute name, and value are always available for interpolation as `model`, `attribute` and `value` respectively. So, for example, instead of the default error message `"cannot be blank"` you could use the attribute name like this : `"Please fill in your %{attribute}"`. diff --git a/guides/source/maintenance_policy.md b/guides/source/maintenance_policy.md index f99b6ebd31..7ced3eab1c 100644 --- a/guides/source/maintenance_policy.md +++ b/guides/source/maintenance_policy.md @@ -44,7 +44,7 @@ from. In special situations, where someone from the Core Team agrees to support more series, they are included in the list of supported series. -**Currently included series:** `5.0.Z`. +**Currently included series:** `5.0.Z`, `4.2.Z`. Security Issues --------------- diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index 2ac5a2188b..a8afa0ca6e 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -44,7 +44,7 @@ TIP: Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterp ### The Update Task -Rails provides the `app:update` task (`rails:update` on 4.2 and earlier). After updating the Rails version +Rails provides the `app:update` task (`rake rails:update` on 4.2 and earlier). After updating the Rails version in the Gemfile, run this task. This will help you with the creation of new files and changes of old files in an interactive session. @@ -94,6 +94,8 @@ class ApplicationRecord < ActiveRecord::Base end ``` +Then make sure that all your models inherit from it. + ### Halting Callback Chains via `throw(:abort)` In Rails 4.2, when a 'before' callback returns `false` in Active Record diff --git a/guides/w3c_validator.rb b/guides/w3c_validator.rb index e3bb964a60..2ce27e2e16 100644 --- a/guides/w3c_validator.rb +++ b/guides/w3c_validator.rb @@ -26,12 +26,11 @@ # # --------------------------------------------------------------------------- -require 'w3c_validators' +require "w3c_validators" include W3CValidators module RailsGuides class Validator - def validate validator = MarkupValidator.new STDOUT.sync = true @@ -57,40 +56,39 @@ module RailsGuides end private - def guides_to_validate - guides = Dir["./output/*.html"] - guides.delete("./output/layout.html") - guides.delete("./output/_license.html") - guides.delete("./output/_welcome.html") - ENV.key?('ONLY') ? select_only(guides) : guides - end + def guides_to_validate + guides = Dir["./output/*.html"] + guides.delete("./output/layout.html") + guides.delete("./output/_license.html") + guides.delete("./output/_welcome.html") + ENV.key?("ONLY") ? select_only(guides) : guides + end - def select_only(guides) - prefixes = ENV['ONLY'].split(",").map(&:strip) - guides.select do |guide| - prefixes.any? {|p| guide.start_with?("./output/#{p}")} + def select_only(guides) + prefixes = ENV["ONLY"].split(",").map(&:strip) + guides.select do |guide| + prefixes.any? { |p| guide.start_with?("./output/#{p}") } + end end - end - def show_results(error_list) - if error_list.size == 0 - puts "\n\nAll checked guides validate OK!" - else - error_summary = error_detail = "" + def show_results(error_list) + if error_list.size == 0 + puts "\n\nAll checked guides validate OK!" + else + error_summary = error_detail = "" - error_list.each_pair do |name, errors| - error_summary += "\n #{name}" - error_detail += "\n\n #{name} has #{errors.size} validation error(s):\n" - errors.each do |error| - error_detail += "\n "+error.to_s.delete("\n") + error_list.each_pair do |name, errors| + error_summary += "\n #{name}" + error_detail += "\n\n #{name} has #{errors.size} validation error(s):\n" + errors.each do |error| + error_detail += "\n "+error.to_s.delete("\n") + end end - end - puts "\n\nThere are #{error_list.size} guides with validation errors:\n" + error_summary - puts "\nHere are the detailed errors for each guide:" + error_detail + puts "\n\nThere are #{error_list.size} guides with validation errors:\n" + error_summary + puts "\nHere are the detailed errors for each guide:" + error_detail + end end - end - end end |