なるようになるブログ

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

rails commit log流し読み(2020/05/25)

2020/05/25分のコミットです。

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


Utilize Symbol#start_with? and #end_with?

SymbolをStringに変換してからstart_with? / end_with?を使用している箇所があったのを、Symbol#start_with? / #end_with?メソッドを使用するよう修正しています。


require "active_support/core_ext/symbol/starts_ends_with" for Ruby 2.6

不足していたactive_support/core_ext/symbol/starts_ends_withの追加、及び、suffixを削除するのにStringに変換+delete_suffixを使用していた箇所を、Symbol#[]を使用するよう修正しています。


Test that Array#extract_options! extracts ActiveSupport::OrderedOptions

activesupport/test/core_ext/array/extract_options_test.rbの修正です。

Array#extract_options!ActiveSupport::OrderedOptionsインスタンスを指定した場合のテストを追加しています。


Fix typo [ci skip]

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

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


Refactor to lazy construct join table aliases

Active Recordの修正です。

join table aliasesの構築処理をlazyに行うようリファクタリングしています。


Merge pull request #39408 from kamipo/remove_limit_on_enum

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

MySQLenumset typeに指定されていたlimitを削除しています。

enumsetがStringとして扱われていた際の名残で、現在は不要な為。


Merge pull request #39415 from kamipo/merge_rewhere_with_non_attrs

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

merge(..., rewhere: true)でnon-attribute nodeも上書き出来るよう対応しています。mergeと同じ挙動にする為。

rails commit log流し読み(2020/05/24)

2020/05/24分のコミットです。

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

activerecord/CHANGELOG.md


Deduplicate same clauses in merge

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

mergeで同じ句を排除するよう修正しています。


Merge pull request #39390 from kamipo/fix_has_many_through_with_join_scope

Active Recordの修正です。

through associationでsource / through scopeをjoinした際に、不正なSQLが生成されてしまうバグがあったのを修正していmさう。


Pass over the "Calling the Mailer" AM guide [ci skip] (#39402)

rails guideのAction Mailer Basicsの修正です。

guide全体の言い回し、グラマーの修正を行っています。


Deprecate aggregations with group by duplicated fields

activerecord/lib/active_record/relation/calculations.rbactiverecord/lib/active_record/relation/query_methods.rbの修正です。

aggregations + groupした場合に、同じfieldsが複数生成されてしまう事がある、という挙動がdeprecateになりました。

accounts = Account.group(:firm_id)
accounts.merge(accounts.where.not(credit_limit: nil)).sum(:credit_limit)
# => {
#   [1, 1] => 50,
#   [2, 2] => 60
# }

元々上記のようになっていたのが、

accounts = Account.group(:firm_id)
accounts.merge(accounts.where.not(credit_limit: nil)).sum(:credit_limit)
# => {
#   1 => 50,
#   2 => 60
# }

になります。同じfieldsが複数含まれるのは元々意図的ではなかった筈、かつ、複数含む必要も無いため。また、annotateにも同様の問題があった為、こちらも同様にdeprecateになっています。


Remove redundant blank? check and compact_blank! for joins_values

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

joins_valuesから不要なblank?チェックとcompact_blank!の呼び出しを削除しています。


Take primay_key in count in ActiveRecord::SignedId (#39404)

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

ActiveRecord::SignedIdでデータ取得時のカラム名id固定になっていたのを、primay_keyメソッド経由でカラム名を取得するよう修正しています。


Copy options before delegating in with_options

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

with_options + nested routesを指定した際に、routesが正しく生成されないバグがあったのを修正しています。


Add delegated type to Active Record (#39341)

Active Recordの修正です。

クラス階層を表す為の処理として、delegated typeという機能をActive Recordに追加しています。

Railsにはクラス階層の為の仕組みとしてSTIがあるのですが、STIだと子クラスに追加したいcolumnを全て親クラスに追加する必要がある(それが他の子クラスでは不要だとしても)、という問題がありました。

delegated typeでは親クラスと子クラスでそれぞれ別のテーブルを保持し、親に共通で使う処理とカラムを保持、子ではの子でのみ必要なカラムと処理を持てるようにしてその問題を解決しています。

例。

# Schema: entries[ id, account_id, creator_id, created_at, updated_at, entryable_type, entryable_id ]
class Entry < ApplicationRecord
  delegated_type :entryable, types: %w[ Message Comment ], dependent: :destroy
end

# Schema: messages[ id, subject ]
class Message < ApplicationRecord
end

# Schema: comments[ id, content ]
class Comment < ApplicationRecord
end

親のEntryクラスで、delegated_typeメソッドを使用して子クラスの定義を行います。関連付けにはポリモーフィックが使用されており、親クラスにはxxx_id及びxxx_typeカラムが必要です。親クラスには子クラスを取得する為のメソッドを定義され、それらのメソッドを使用し、子クラスの処理を呼び出せるようになっています。

Entry.messages
#  SELECT "entries".* FROM "entries" WHERE "entries"."entryable_type" = ? LIMIT ?  [["entryable_type", "Message"], ["LIMIT", 11]]
# => #<ActiveRecord::Relation [#<Entry id: 1, entryable_type: "Message", entryable_id: 1, created_at: "2020-05-24 05:42:38.420043000 +0000", updated_at: "2020-05-24 05:42:38.420043000 +0000">]>

Entry.first.message_id
Entry.first.message.subject

使い方等の詳細は、API Doc ActiveRecord::DelegatedType参照。


Default engine ENGINE=InnoDB is no longer dumped to make schema more agnostic

Active Recordの修正です。

schemaファイルにengineの値を出力しないよう修正しています。

元々はlarge keyでutf8mb4を使用する為に出力していました。しかし現在Active RecordでサポートしているMySQLではこの情報が不要になった(デフォルトのrow formatがDYNAMICになった)為、出力しないよう修正しています。


Separate primary key column options from table options

Active Recordの修正です。

primary key column optionsをtable optionsから分離しています。columnとtableで同じ名前のオプションを扱えるようにする為。


Do not use object_id on Active Record object directly

Active Recordの修正です。

Active Record objectのobject_idを使用していた箇所を修正しています。

object_idという名前のattributeを定義する事が出来てしまう、かつ、その場合に想定外の挙動になってしまうのを避ける為。


Update rubocop-performance gem and enable Performance/DeletePrefix and Performance/DeleteSuffix cops

rubocop-performance gemのバージョンを1.6.0に更新、及び、Performance/DeletePrefixPerformance/DeleteSuffix copを有効化するよう修正しています。


"Neither relation may have a #limit, #offset, or #distinct set." is not true

activerecord/lib/active_record/relation/query_methods.rbのdocの修正です。

orメソッドのdocに、orに指定するrelationには#limit#offset、または#distinctが指定されてある必要がある旨説明があったのを削除しています。現状その制限は無い為。


[skip-ci] Fix delegated_type examples

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

delegated_typeメソッドのdoc内のレコード作成のexampleの内容に誤りがあったのを修正しています。


Allow relations with different SQL comments in or

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

annotateoptimizer_hintsが指定されているrelationもorに指定出来るよう修正しています。

rails commit log流し読み(2020/05/23)

2020/05/23分のコミットです。

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


Reduce allocations in action_view cache expiry

actionview/lib/action_view/cache_expiry.rbの修正です。

dirs_to_watchメソッドでmutatingメソッドを使用してオブジェクト生成数を減らすよう修正しています。


Test Attached::Many in Attached::Many test

activestorage/test/models/attached/many_test.rbの修正です。

many_test.rbAttached::Oneに関するテストをしていたのを、Attached::Manyのテストを行うよう修正しています。

rails commit log流し読み(2020/05/22)

2020/05/22分のコミットです。

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


Update Railties tests for 7e52d0a

railtiesのテストの修正です。

古いredict URLをroutes.rbに定義した、Preserve old redirect URLsの影響でrailtiesのテストがコケてしまっていたのを修正しています。


Allow Erubi bufvar to be configured

actionview/lib/action_view/template/handlers/erb/erubi.rbの修正です。

Erubiのbufvar optionを指定出来るよう修正しています。

render_inを実装したcomponentで現在のoutput bufferを参照出来るようにするため。


Optimise serializable_hash when options are empty

activemodel/lib/active_model/serialization.rbの修正です。

serializable_add_includesメソッドで不要なHashオブジェクトを生成しないようにした、Reduce allocations in to_json's include optionをRevertしています。

activemodel-serializers-xml経由でのserialization処理が壊れてしまった為。

rails commit log流し読み(2020/05/21)

2020/05/21分のコミットです。

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


Whitespaces

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

attributeの宣言とメソッドの間に空行を追加しています。


[ci skip] Add ActionDispatch::ActionableExceptions to default middleware docs

rails guideのRails on Rackの修正です。

デフォルトでロードされるミドルウェアの一覧にActionDispatch::ActionableExceptionsを追加しています。


Updates to nokogiri 1.10.9

Gemfile.lockの修正です。

nokogiri gemのバージョンを1.10.9に更新しています。


Merge pull request #39379 from zenspider/zenspider/fix-backtrace-in-master

railties/lib/rails/test_unit/reporter.rbの修正です。

Fixed BacktraceCleaner to never return an empty backtrace.の対応の影響で、テスト失敗時のバックトレースが表示されなくなってしまっていたのを修正しています。


Decoding JSON dates should respect newlines

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

JSONのdecode処理で、改行がある場合(e.g. "Date is\n2020-01-01"})もDATE / DATETIMEと見なされてしまうバグがあったのを修正しています。


Merge pull request #39378 from kamipo/fix_has_many_through_with_source_scope

activerecord/lib/active_record/associations/preloader/association.rbの修正です。

through associationをincludes / preloadする際に、associationに指定されているscopeが無視されてしまうバグがあったのを修正しています。


Preserve old redirect URLs

activestorage/config/routes.rbの修正です。

Active Storageのproxy対応で変更になったredirect URLについて、古いURLについてもroutes.rbに定義するよう修正しています。

古いURLがキャッシュされて使用される可能性がある為。

rails commit log流し読み(2020/05/20)

2020/05/20分のコミットです。

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

actionpack/CHANGELOG.md

actionview/CHANGELOG.md

activerecord/CHANGELOG.md


Update aws-sdk-s3 dependency

activestorage/lib/active_storage/service/s3_service.rbの修正です。

aws-sdk-s3のバージョン指定を~> 1.14から~> 1.48.0に修正しています。

先日のセキュリティリリースで追加したオプション(whitelist_headers)が1.48.0で追加されたオプションな為。


Stop calling methods directly on Journey

actionpack/test/journey/router_test.rbの修正です。

テストでJourneyのメソッドを直接呼び出していたのを、Action Dispatch経由で処理を行うよう修正しています。

Journeyのメソッドはprivate APIで、リファクタリングにより使えなくなる可能性がある為。


Update active_record_callbacks.md

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

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


Merge pull request #39312 from eugeneius/parameters_compact

actionpack/lib/action_controller/metal/strong_parameters.rbの修正です。

ActionController::Parameterscompact / compact!メソッドを追加しています。


Consolidate build_left_outer_joins into build_joins

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

build_left_outer_joinsメソッドの処理をbuild_joinsメソッドに統合しています。


Fix index options for if_not_exists/if_exists

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

add_indexにnamed indexを指定 + second indexに同じカラムを違う名前で指定した場合にindexが追加されないバグがあったのを修正、及び、remove_indexにnamed indexを指定 + カラムにnilを指定した場合にindexが削除されるよう修正しています。


More refactor build_joins

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

build_joins内のbuckets生成処理を別メソッドにするよう修正しています。


Reduce allocations in to_json's include option

activemodel/lib/active_model/serialization.rbの修正です。

serializable_add_includesメソッドで不要なHashオブジェクトを生成しないよう修正しています。


Clarify subheadline of maintenance policy

rails guideのMaintenance Policy for Ruby on Railsの修正です。

Railsのバージョンのフォーマットについて説明している箇所に、security release以外のフォーマットである旨説明を追加しています。


Merge pull request #39204 from prathamesh-sonpatki/template-annotation

テンプレート名のコメントへの出力処理を行うかどうかを指定する為のconfig名をannotate_template_file_names -> annotate_rendered_view_with_filenamesに変更、及び、rails newで生成するenvファイルにconfigを記載するよう修正しています。


Unify raise_on_missing_translations for views and controllers

Action Pack、Action Viewの修正です。

controllerでもraise_on_missing_translationsオプションを指定出来るよう修正しています。

それに伴い、Action Packでも使用するならconfig名がconfig.action_view.raise_on_missing_translationsだとおかしい為、config名がconfig.i18n.raise_on_missing_translationsに変更なり、古いconfig名はdeprecateになりました。


Move tests higher up the stack

actionpack/test/journey/router_test.rbの修正です。

Stop calling methods directly on Journeyで行われた変更について、Rack::Utilsを使って処理を行うよう修正しています。


Resolve conflict between counter cache and optimistic locking

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

optimistic lockingを使用している場合に、counter cacheで値を更新後に同じインスタンスで更新処理を行おうとするとActiveRecord::StaleObjectErrorが発生してしまうバグがあったのを修正しています。


Satisfy Rubocop

actionpack/test/journey/router_test.rbの修正です。

rubocopの設定に違反している箇所があったのを修正しています


loaded should be aliased to loaded? in collection proxy

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

CollectionProxyloaded?のaliasとしてloadedを定義して、loadedloaded?が同じ結果を返すよう修正しています。

rails commit log流し読み(2020/05/19)

2020/05/19分のコミットです。

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


Merge branch 'master-sec'

セキュリティリリース(6.0.3.1、5.2.4.3)の修正をmasterにコミットしています。修正内容は下記の通り。

[CVE-2020-8162] Circumvention of file size limits in ActiveStorage

Active StorageでS3にdirect uploadする際に、Content-Lengthの改ざんが出来てしまっていた(ユーザが指定したContent-Lengthがそのまま使用されてしまっていた)のを修正。

[CVE-2020-8164] Possible Strong Parameters Bypass in ActionPack

ActionController::Parameterseacheach_valueeach_pair の戻り値がuntrustedな値になっていた(permitした値ではなくraw parameterがそのまま返されていた)のを修正。

[CVE-2020-8165] Potentially unintended unmarshalling of user-provided objects in MemCacheStore and RedisCacheStore

ユーザから入力された情報をrawデータとしてMemCacheStore / RedisCacheStoreに書きこんだ後に、そのデータを読み込む際にその入力された情報がMarshalled objectとしevaluateされてしまっていたのを修正。

[CVE-2020-8166] Ability to forge per-form CSRF tokens given a global CSRF token

global CSRF tokenが指定されていた場合、それを使ってフォーム毎のCSRF tokenが偽造出来てしまっていたのを修正。

[CVE-2020-8167] CSRF Vulnerability in rails-ujs

rails-ujsで不正なドメインCSRF tokensを送れてしまっていたのを修正。


Fix syntax error

activestorage/lib/active_storage/service/s3_service.rbの修正です。

先にマージされたコードの中にシンタックスエラーになる箇所があったのを修正しています。


Unify the query values normalization for multiple values

Active Recordの修正です。

query valuesのnormalizationが箇所によってやりかたが異なっていたのを、同じnormalizationを行うよう修正しています。


Fix test_two_classes_autoloading failure

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

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


Fix references in the form builders guide [ci skip]

rails guideのAction View Form Helpersの修正です。

exampleコードとそのコードについて説明している箇所で、変数名が一致してない箇所があったのを修正しています。


Test multiple values with blank value

activerecord/lib/active_record/relation/query_methods.rbactiverecord/test/cases/relations_test.rbの修正です。

multiple value methodsに空の値を指定した場合のテストを追加しています。


Update fixture_file_upload documentation to reflect recent changes. (#39340)

actionpack/lib/action_dispatch/testing/test_process.rbの修正です。

Use the file_fixture_path for fixture_file_upload:の挙動変更(file_fixture_path相対パスで検索されるようになる)に合わせて、ドキュメントも修正しています。


Add DidYouMean for HasManyThroughAssociationNotFoundError

activerecord/lib/active_record/associations.rbactiverecord/lib/active_record/reflection.rbの修正です。

ActiveRecord::HasManyThroughAssociationNotFoundErrorエラーが発生した場合に、did_you_meanを使用してサジェスチョンを出すよう修正しています。


Add DidYouMean for ParameterMissing

actionpack/lib/action_controller/metal/strong_parameters.rbの修正です。

ActionController::ParameterMissingエラーが発生した場合に、did_you_meanを使用してサジェスチョンを出すよう修正しています。