なるようになるブログ

読書感想文かrailsについてかrubyについてか

rails commit log流し読み(2017/04/21)

2017/04/21分のコミットです。

CHANGELOGにのったコミットは以下の通りです。

railties/CHANGELOG.md

activerecord/CHANGELOG.md

activejob/CHANGELOG.md


Namespace CSS selectors on error pages

railties/lib/rails/generators/rails/app/templates/public/404.htmlrailties/lib/rails/generators/rails/app/templates/public/422.htmlrailties/lib/rails/generators/rails/app/templates/public/500.htmlの修正です。

デフォルトのエラーページでスタイルをあてる際に、bodyタグやh1タグに直接スタイルをあてていたのを、エラー表示用のクラスを作成し、そちらを使用するよう修正しています。

-<body>
+<body class="rails-default-error-page">

bodyに直接スタイルを指定してしまうと、Turbolinksを使っている場合に問題がある為(エラーページを表示して、前のページに戻った際に、bodyタグのスタイルがそのまま残ってしまうケースがある)為対応したとの事です。


Fixes Hash.from_xml with frozen strings for all backends

Active Supportの修正です。

Hash.from_xmlにfreeze済みのStringを渡した場合にエラーになってしまうバグがあったのを修正しています。IO#ungetcを使っているのが問題だった為、使用しないよう修正しています。


Merge pull request #28582 from sbull/activejob-error-logging

activejob/lib/active_job/logging.rbの修正です。

Active Jobでjob実行時のログを取得する際に、エラーが発生した場合はそのエラーの情報をログに出力するよう修正しています。

例。

Performing GuestJob (Job ID: eea34ed0-106b-4cfa-8e56-4a3c55244417) from Async(default) with arguments: "dummy"
Error performing GuestJob (Job ID: eea34ed0-106b-4cfa-8e56-4a3c55244417) from Async(default) in 0.14ms: RuntimeError (Dummy!):
/home/yaginuma/program/rails/master/app/jobs/guest_job.rb:5:in `perform'
/home/yaginuma/program/rails/master_y_yagi/rails/activejob/lib/active_job/execution.rb:37:in `block in perform_now'
/home/yaginuma/program/rails/master_y_yagi/rails/activesupport/lib/active_support/callbacks.rb:108:in `block in run_callbacks'
/home/yaginuma/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/i18n-0.8.1/lib/i18n.rb:257:in `with_locale'
...

backtraceがそのまま全て表示されるようになっています。


Merge pull request #28681 from runephilosof/fix-mysql-grant

activerecord/lib/active_record/tasks/mysql_database_tasks.rbの修正です。

db:create taskでGRANTステートメントを発行する際に、database名をエスケープするよう修正しています。


Prevent double firing the before save callback of new object when the parent association saved in the callback https://github.com/rails/rails/commit/c0038f7c362fa0c92fc9e1ea3bdb2706f42386c6

Active Recordの修正です。

has_manyの子モデルのbefore_save内で親レコードをsaveするcallbackを仕込んでると、子レコードをsaveするときsave完了前にcallback内の親レコードから子レコードのbefore_saveがもう一回発火してしまうバグがあったのを修正しています。


Add comma

activesupport/lib/active_support/core_ext/enumerable.rbのdocの修正です。

Enumerable module内のdocのコメントにカンマを追加しています。


Add missing require

activejob/test/cases/logging_test.rbの修正です。

不足していたjobs/rescue_jobのrequireを追加しています。


Don’t attempt to create a new record that was already created.

activerecord/lib/active_record/autosave_association.rbの修正です。

association同士でhas_and_belongs_to_manyを設定していた場合に、データ保存時に複数レコードが生成されてしまうバグがあったのを修正しています。

class Organisation < ActiveRecord::Base
  has_one :user
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :roles
  belongs_to :organisation
end

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users
end

user = User.new
user.organisation = Organisation.new
user.roles << Role.new
user.save!

User.first.roles.count
# => 1になるべきが、2になってしまっていた

Merge pull request #28432 from marksiemers/master

rails guideのForm Helpersの修正です。

Building Complex Formsの項のmodelのexampleコードに、inverse_ofオプションを追加しています。inverse_ofの指定が無いと、以降のexampleコードが正しく動作しない為。


Add test case to make sure we can implicit convert a Parameters to a Hash

actionpack/test/controller/parameters/parameters_permit_test.rbの修正です。

ActionController::Parametersが暗黙的にHashに変換される事を確認する為のテストを追加しています。

rails commit log流し読み(2017/04/20)

2017/04/20分のコミットです。

CHANGELOGにのったコミットは以下の通りです。

actionpack/CHANGELOG.md

activesupport/CHANGELOG.md

activerecord/CHANGELOG.md

actioncable/CHANGELOG.md


Merge pull request #28794 from vishalzambre/activerecord-guid

rails guideのActive Record Migrationsの修正です。

Types of Schema Dumpsの項、DB固有の項目(トリガー、シーケンス)等の扱いについての説明の箇所がハイライトされるよう、先頭にNOTE:を追加しています。


Reword sentence

rails guideのActive Record Migrationsの修正です。

Types of Schema Dumpsの項のグラマー、言い回しを修正しています。


Merge pull request #28734 from rafaelfranca/strong-parameters

Action Packの修正です。

ActionController::Parametersに対して以下の対応を行っています。

  • Hashを返すActionController::Parameters#to_hashメソッドの追加
    • #to_hHashWithIndifferentAccess返すのに対して、こちらはHashを返します
  • permitしていないActionController::Parametersクラスのオブジェクトに対してto_hメソッドを呼び出した場合に、エラー(UnfilteredParameters)をraiseするよう修正
    • 元々は空のHashか、デフォルトでpermitされる:controller:actionだけが返るようになっていました。しかしto_hを呼び出して値が空の場合にto_unsafe_hを呼びだす、というコードが多く発生してしまい、これはセキュリティ的に良くないだろう、という事で、permitされてない場合は明示的にエラーとするようにしたようです。
  • ActionController::Parameters#to_query#to_paramメソッドを追加
    • 元々はpermitされてない値が使用される可能性がある為実装されていなかったのですが、#to_hがエラーをraiseするようになり、#to_hメソッドを使用すればpermitされてない場合はエラーになるようなった為、実装を追加との事です

Send deprecation horizon and gem name as arguments to deprecation heavier handler, and make sure they are used for the ActiveSupport::Notifications message.

Active Supportの修正です。

deprecation notificationsにgem名とdeprecation horizon(削除されるバージョン)を渡せるよう修正しています。gem名は元々はdeprecations.railsが固定で設定されていたのですが、rails以外で使いたいケースがあった為との事です。


Merge pull request #28166 from bogdanvlviv/fix_migration_tasks

activerecord/lib/active_record/migration.rbの修正です。

最初のマイグレーションまでrollbackされた状態でdb:forward taskを実行してもマイグレーションが実行されないバグがあったのを修正、及び、マイグレーションが存在しない場合にdb:rollbackdb:forward taskを実行した場合にエラー(UnknownMigrationVersionError)をraiseするよう修正しています。


Merge pull request #28757 from edwardmp/log-actioncable-write-read-errors

actioncable/lib/action_cable/connection/base.rbの修正です。

socketで処理が発生した場合に、エラーを無視していたのをエラーの内容をログに出力するよう修正しています。

      def on_error(message) # :nodoc:
-        # ignore
+        # log errors to make diagnosing socket errors easier
+        logger.error "WebSocket error occurred: #{message}"
       end

Use released sass-rails instead of master version

railties/lib/rails/generators/app_base.rbの修正です。

新規に作成するrailsアプリのGemfileで、Githubのmasterブランチではなく、リリース済みのgemを使用するようまとめて修正しています。


Fix all style guides violations

rubocopのバージョンを0.48.0に更新、及び、rubocopのルールに違反していた箇所をまとめて修正しています。


Merge pull request #28708 from y-yagi/dont_generate_system_test_files

railties/lib/rails/generators/rails/app/templates/config/application.rbの修正です。

skip_system_testオプションを指定してrailsアプリを作成した場合、scaffoldでsystem testに関するファイルが生成されないようにする為に、application.rbgenerators.system_tests = nilを設定するよう修正しています。


Merge pull request #28776 from kamipo/respect_limit_for_cache_key

activerecord/lib/active_record/collection_cache_key.rbの修正です。

ActiveRecord::CollectionCacheKey#collection_cache_keyメソッドでrelationからcache keyを生成する際に、relationがload済みの場合はrelationに指定されたlimitに依存したsizeを取得していたのを、loadされてないない場合はlimitが無視されていました。

で、これをrelationがloadされていない場合もlimitを考慮したsizeを取得するよう修正しています。


Merge pull request #28733 from kamipo/dont_fallback_to_utf8mb3_after_mysql_8.0.0

Active Recordの修正です。

MySQL 8.0.0以降では、Rails内部用のテーブルを作成する際に、utf8mb3にフォールバックしないよう修正しています。

+        def internal_string_options_for_primary_key
+          super.tap do |options|
+            if CHARSETS_OF_4BYTES_MAXLEN.include?(charset) && (mariadb? || version < "8.0.0")
+              options[:collation] = collation.sub(/\A[^_]+/, "utf8")
+            end
+          end
+        end
+
         private
+          CHARSETS_OF_4BYTES_MAXLEN = ["utf8mb4", "utf16", "utf16le", "utf32"]
+

MySQL 8.0系でデフォルトのcollationが変わった為(fallback先のcollationがもう無い為)対応したようです。また、そもそも、MySQL 5.7以降はinnodb_default_row_formatでrow formatを指定出来るようになっており、fallbackしないでも大丈夫な為、という理由のようです。 あってるか大分不安。


Remove outdated comment

activesupport/lib/active_support/callbacks.rbのdocの修正です。

CallbackChainクラスのdocにArray + compileメソッドが定義されているクラスである旨説明が記載されていたのですが、use delegation over inheritance so we can figure when to cache / bust cacheでArrayを継承しなくなっていたので、コメントを消しています。

rails commit log流し読み(2017/04/19)

2017/04/19分のコミットです。

CHANGELOGへの追加はありませんでした。


Merge pull request #28788 from tjschuck/require_as_notifications_in_cache

activesupport/lib/active_support/cache.rbの修正です。

active_support/notificationsのrequireを追加しています。が、直後にrevertされています。


Revert “Merge pull request #28788 from tjschuck/require_as_notifications_in_cache”

という訳で、直前のrequireをrevertしています。

ActiveSupport::Notificationsはトップレベルのactive_support.rbでautoloadするよう設定されており、個別にrequireする必要は無い為。


Explicitly require AS::Time in AS::Testing::TimeHelpers

activesupport/lib/active_support/testing/time_helpers.rbの修正です。

不足していたactive_support/core_ext/time/calculationsのrequireを追加しています。


Merge pull request #28161 from bogdanvlviv/add_test_attributes

activerecord/test/cases/base_test.rbの修正です。

ActiveRecord::AttributeMethods#attributesメソッドについてのテストを追加しています。


Remove datetime fields from helper list [ci skip]

rails guideのForm Helpersの修正です。

Other Helpers of Interestの項にあるヘルパーメソッドの一覧からdatetime fieldsを削除しています。Change datetime to datetime-local helper tagの対応でdatetime_fielddatetime_local_fieldのaliasになり、datetime fieldsを生成する為のメソッドは今は無い為。


Use quoted_scope rather than @config[:database] to respect current database

activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rbの修正です。

MySQL::ColumnDumper#extract_expression_for_virtual_columnメソッドでschema、table名のescap処理にquote用のラッパーメソッド(quoted_scope)を使用するよう修正しています。


Fix extract_expression_for_virtual_column for MariaDB

ctiverecord/lib/active_record/connection_adapters/mysql/schema_dumper.rbの修正です。

MySQL::ColumnDumper#extract_expression_for_virtual_columnメソッドでMariaDBの場合のexpression取得用正規表現COLLATE句のチェック処理を追加しています。

          def extract_expression_for_virtual_column(column)
             if mariadb?
               create_table_info = create_table_info(column.table_name)
-              if %r/#{quote_column_name(column.name)} #{Regexp.quote(column.sql_type)} AS \((?<expression>.+?)\) #{column.extra}/m =~ create_table_info
+              if %r/#{quote_column_name(column.name)} #{Regexp.quote(column.sql_type)}(?: COLLATE \w+)? AS \((?<expression>.+?)\) #{column.extra}/ =~ create_table_info
                 $~[:expression].inspect
               end

rails commit log流し読み(2017/04/18)

2017/04/18分のコミットです。

CHANGELOGへの追加はありませんでした。


Add (more) documentation to to_time

activesupport/lib/active_support/core_ext/date/conversions.rbのdocの修正です。

to_timeメソッドのdocにアプリで指定したtimezoneが設定された値が必要な場合、in_time_zoneメソッドを使うよう説明を追加しています。


Small docs fix

rails guideのGetting Started with Railsの修正です。

What is Rails?の項のRuby languageRuby programming languageに修正しています。


Add missing periods

activesupport/lib/active_support/core_ext/date/conversions.rbのdocの修正です。

to_timeメソッドのdocの終端にピリオドを追加しています。


Use more specific check for :format in route path

actionpack/lib/action_dispatch/routing/mapper.rbの修正です。

route pathに:format が含まれているかどうかを、より厳密にチェックするよう修正しています。

元々はpathに:formatという文字が含まれているかどうかでチェックしていたのですが、それだと/formats/:format_id/itemsというようなpathの場合に、:format_idという部分がマッチしてしまい、予期せぬ挙動となってしまう為、正規表現(%r{(?:\(\.:format\)+|\.:format|/)\Z})にマッチするかどうかで見るよう修正しています。


Fix Enumerable#sum redefined warning

activesupport/lib/active_support/core_ext/enumerable.rbの修正です。

Ruby 2.4以上でEnumerable#sumを再定義する事によるwarningが出てしまっていたので、Enumerable#sumが定義されている場合はそちらを使用するよう修正しています。

rails commit log流し読み(2017/04/17)

2017/04/17分のコミットです。

CHANGELOGへの追加はありませんでした。


Bump the bundled GlobalID version.

Gemfile.lockの修正です。

globalidのバージョンを0.4.0に更新しています。


Add Puerto Rico support to ActiveSupport::TimeZone

activesupport/lib/active_support/values/time_zone.rbの修正です。

タイムゾーンの一覧にPuerto Rico(America/Puerto_Rico)を追加しています。


There are actually only 134 unique timezones.

activesupport/lib/active_support/values/time_zone.rbのdocの修正です。

ActiveSupport::TimeZoneクラスのコメントにある提供されているタイムゾーンの数が実際の数と異なっていたのを修正しています。


Small grammar fixes

rails guideのWorking with JavaScript in Railsの修正です。

各項のグラマー、フォーマットの修正をまとめて行っています。


Small grammar fix

rails guideのWorking with JavaScript in Railsの修正です。

グラマーの修正を行っています。


Fix the doc on the IndexDefinition [ci skip]

activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rbのdocの修正です。

ConnectionAdapters::IndexDefinitionクラスのdoc内のindexesメソッドが定義されているmodule名に誤りがあったのを修正しています。


Add missing word ‘to’ [ci skip]

rails guideのCreating and Customizing Rails Generators & Templatesの修正です。

Application Templatesの項のグラマーの修正を行っています。


Merge pull request #28685 from rails/smooth-form-with-upgrading

form_withメソッドのlocalオプションをconfig(config.action_view.form_with_generates_remote_forms)で指定出来るよう修正しています。 app:updateでアップデートした場合、new_framework_defaults_5_1.rbfalse(ajax通信を行わない)が指定されるようになっています。

合わせて、embed_authenticity_token_in_remote_formsのデフォルトをfalseからnilに変更しています。明示的に値が指定されてなかった場合)を"auto"として扱えるようにする(ユーザがfalseを指定した場合と区別出来るようにする)為、との事です。

rails commit log流し読み(2017/04/16)

2017/04/16分のコミットです。

CHANGELOGにのったコミットは以下の通りです。

activerecord/CHANGELOG.md


Revert parts of cad58fb

rails guideのRuby on Rails 5.1 Release Notesの修正です。

Changelogへのリンクをコンポーネントの項の先頭に移動、及びNotable ChangesNotable changesに修正しています。


Refactor indexes things in connection adapters

Active Recordの修正です。

IndexDefinitionクラスの引数の指定にキーワード引数を使用するよう修正、及び、indexesメソッドを全てのadapterでSchemaStatements moduleに定義するようリファクタリングしています。


Support Descending Indexes for MySQL

activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rbactiverecord/lib/active_record/connection_adapters/mysql/schema_statements.rbの修正です。

MySQL 8.0.1からサポートされたDescending Indexesをmigrationファイルで使用出来るよう修正しています。

Descending Indexesとは、名前の通り、INDEXにDESC(元々のスキャンが降順で行われていたので、DESCを指定すると昇順になる)を指定出来るようにする機能のようです。

CREATE TABLE t (
  c1 INT, c2 INT,
  INDEX idx1 (c1 ASC, c2 ASC),
  INDEX idx2 (c1 ASC, c2 DESC),
  INDEX idx3 (c1 DESC, c2 ASC),
  INDEX idx4 (c1 DESC, c2 DESC)
);

Ref: MySQL :: MySQL 8.0 Reference Manual :: 9.3.12 Descending Indexes


Use the config value directly when call secrets

railtiesの修正です。

configファイル内でsecretsメソッドを呼び出した際に、encrypyed secretsで定義した情報が取得出来ないバグがあったのを修正しています。


Let run_secrets_generator handle chdir.

railties/test/secrets_test.rbの修正です。

encrypyed secretsのテストで、不要なchdirがあったのを削除しています。

rails commit log流し読み(2017/04/15)

2017/04/15分のコミットです。

CHANGELOGにのったコミットは以下の通りです。

activesupport/CHANGELOG.md

activerecord/CHANGELOG.md


Add additional options to time change methods

activesupport/lib/active_support/core_ext/time/calculations.rbactivesupport/lib/active_support/time_with_zone.rbの修正です。

Time#change``メソッドに:offsetオプションを指定出来るよう対応しています。合わせて、ActiveSupport::TimeWithZone#change:offset:zone`オプションを指定出来るよう対応しています。

t = Time.zone.now
# => Sat, 15 Apr 2017 05:56:34 UTC +00:00

t.change(offset: "-10:00")
# => Sat, 15 Apr 2017 05:56:34 HST -10:00

t.change(zone: "Hawaii")
# => Sat, 15 Apr 2017 05:56:34 HST -10:00

Merge pull request #28661 from bogdanvlviv/fix-dirty-attributes-if-override-attr_accessor

activemodel/lib/active_model/dirty.rbactiverecord/lib/active_record/attribute_methods/dirty.rbの修正です。

attributes readerをオーバーライドしている時(テーブルのカラム名と同じ名前のメソッドがある場合)にdirty methodが返す値に一貫性が無かった(オーバーライドされたメソッドが呼ばれる場合と呼ばれないケースがあった)のを、処理を統一するよう修正しています。

# app/models/user.rb

class User < ApplicationRecord
  def email
    super.upcase
  end
end
# before
user = User.create!(email: "test@example.com")
#<User id: 3, name: nil, email: "test@example.com", created_at: "2017-04-15 06:00:48", updated_at: "2017-04-15 06:00:48">

user.email = "dummy@example.com"
# => "dummy@example.com"

user.changes["email"]
# => ["test@example.com", "DUMMY@EXAMPLE.COM"]


# after
user = User.create!(email: "test@example.com")
#<User id: 3, name: nil, email: "test@example.com", created_at: "2017-04-15 06:00:48", updated_at: "2017-04-15 06:00:48">

user.email = "dummy@example.com"
# => "dummy@example.com"

user.changes["email"]
# => ["test@example.com", "dummy@example.com"]

Move around AR::Dirty and fix _attribute method

activemodel/lib/active_model/attribute_methods.rbactivemodel/lib/active_model/dirty.rbの修正です。

先のdirty methodについての対応で、attributeの値を取得するために_attributesというメソッドを追加していたのですが、すでに同じ用途の為の_read_attributeというメソッドがある為、そちらを使用するよう修正しています。


Fix module name [ci skip]

actionview/lib/action_view/helpers/form_helper.rbのdocnの修正です。

form_withメソッドのdocでFormOptionsHelperFormOptionHelperにタイポしていたのを修正しています。


Rename association_query_handler.rb to association_query_value.rb

Active Recordの修正です。

association_query_handler.rbassociation_query_value.rbに、polymorphic_array_handler.rbpolymorphic_array_value.rbにそれぞれリネームしています。

Convert association queries to PORO queriesの対応で、AssociationQueryHandlerクラス、PolymorphicArrayHandlerクラスは無くなり、上記のファイルにはAssociationQueryValueクラス、PolymorphicArrayValueクラスが残っている為、クラス名に合わせてファイル名を修正しています。


Early return in PredicateBuilder::ArrayHandler

activerecord/lib/active_record/relation/predicate_builder/array_handler.rbの修正です。

PredicateBuilder::ArrayHandler#callメソッドで、メソッドの先頭でearly returnするよう修正しています。


Merge pull request #28709 from prathamesh-sonpatki/release-notes-1

rails guideのRuby on Rails 5.1 Release Notesの修正です。

コンポーネントNotable Changesの項にエントリーを追加しています。


Merge pull request #28638 from bogdanvlviv/prepend_and_append_in_ruby

activesupport/lib/active_support/core_ext/array/prepend_and_append.rbの修正です。

Array#appendArray#prependメソッド定義前にメソッドがRuby本体にメソッドが定義されてないかチェックするよう修正しています。

参考:array.c: Array#append and Array#prepend