なるようになるブログ

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

rails commit log流し読み(2018/02/28)

2018/02/28分のコミットです。

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

actionview/CHANGELOG.md

activerecord/CHANGELOG.md


Don't enforce UTF-8 by default

Action Viewの修正です。

長らく古いIE(8以下)でUnicodeエンコードされるようにする為に、デフォルトでutf8=✓がinput要素に生成されいたのですが、流石にもうIE8以下向けのサポートは無くて大丈夫だろうという事で、デフォルトでは生成しなくないました。

config(config.action_view.default_enforce_utf8)にtrueを指定すると、5.2までと同じように自動で生成されるように出来るようになっています。


Merge pull request #31966 from kg8m/fix_limited_ids_for

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

associationをeager load + そのeager loadしたassociationのprimary keyをorderに指定 + limitを指定した場合に、eager loadしたassociationの方のprimary keyが値取得時の条件につかわれてしまい、結果正しく値が取得出来ない事がある、というバグがあったのを修正しています。


Merge pull request #32121 from benoittgt/move-rails-routes-to-rails-command

railtiesの修正です。

rake taskとして実装されていたroutes taskを、rails commandとして実装するよう修正しています。

routesにオプション(--expanded)を追加出来るようにする為、との事です。


Merge pull request #32127 from zamith/zamith/screenshot-absolute-path

actionpack/lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rbの修正です。

system testで失敗した際に表示するscreenshotのpathを相対パスから絶対パスに変更しています。

パスをクリックした際にブラウザで開けるようにする為との事です。


Let select render default selected option for required field

actionview/lib/action_view/helpers/tags/base.rbの修正です。

selectメソッドでpromptオプションとdisabledselectedオプションを同時に指定出来なかったのを、指定出来るよう修正しています。

# before
select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {prompt: 'Select Person', selected: '', disabled: ''})

# =>
# <select name="post[person_id]" id="post_person_id">
#   <option value="">Select Person</option>
#   <option value="1">David</option>
#   <option value="2">Eileen</option>
#   <option value="3">Rafael</option>
# </select>


# after
select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {prompt: 'Select Person', selected: '', disabled: ''})
# =>
# <select name="post[person_id]" id="post_person_id">
#   <option value="" disabled="disabled" selected="selected">Select Person</option>
#   <option value="1">David</option>
#   <option value="2">Eileen</option>
#   <option value="3">Rafael</option>
# </select>

Fix new_framework_defaults_6_0.rb

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

config.action_view.default_enforce_utf8config.action_controller.default_enforce_utf8にタイポしていたのを修正しています。


Use with_partial_writes helper in activerecord/test/cases/dirty_test.rb

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

テスト内でpartial_writesの値を変更するのに、それようのヘルパーメソッド(with_partial_writes)を使用するよう修正しています。


Merge pull request #31171 from sambostock/improve-abstract-class-documentation

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

ActiveRecord::Base.abstract_classメソッドのdocに、abstract classを使う場合のexampleを追加しています。


Merge pull request #31926 from composerinteralia/am-attributes

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

ActiveModel::Attributesattributesメソッドを追加しています。

Active Recordと同様にattributesのHashを取得出来るようにする為。


Fix a typo in activerecord/CHANGELOG.md

activerecord/CHANGELOG.mdの修正です。

CHANGELOGのエントリーでcolumns_for_distinctcolumsn_for_distinctにタイポしていたのを修正しています。


Add separate test to ensure that delegate with :private option returns correct value

activesupport/lib/active_support/core_ext/module/delegation.rbactivesupport/test/core_ext/module_test.rbの修正です。

delegateメソッドのグラマーの修正、及び、delegateprivateオプションを指定した場合に正しい値が取得出来る事を確認する為のテストを既存のテストから切り出しています。


Don't include unused ActiveSupport::Concern

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

使用していないActiveSupport::Concernのextendを削除しています。


Alias assign_attributes to attributes= for AttributeAssignment

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

ActiveRecord::AttributeAssignment moduleに定義されていたattributes=メソッドをActiveModel::AttributeAssignment moduleでaliasとして定義するよう修正しています。

元々定義されていたattributes=assign_attributesを呼び出すだけになっており、Active Record側にメソッドを定義しておく必要性は無い為、のようです。


Remove CHANGELOG entries which were backported to 5-2-stable

各CHANGELOから5.2にバックポートされたエントリーを削除しています。

rails commit log流し読み(2018/02/27)

2018/02/27分のコミットです。

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

actionview/CHANGELOG.md

activemodel/CHANGELOG.md


Avoid specifying content types for direct uploads to Google Cloud Storage

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

Google Cloud Storageにdirect uploadする際に、content typeを指定しないよう修正しています。

content typeが指定された状態だと、本来指定したいcontent type(signed URLsのparamに指定したresponse-content-type)が指定されない為。

参考:Fix customizing Content-Type via GCS service URLs


Never attempt to write virtual attributes to the database

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

partial_writesがfalseの場合に、databaseへの値の保存処理で virtual attributesも保存しようとしてしまっていたのを、保存しないよう修正しています。


Ensure we don't write virtual attributes on update, too

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

partial_writesがfalseの場合に、更新処理でvirtual attributesも保存しようとしてしまっていたのを、保存しないよう修正しています。


Partly revert 91b30a001b79096b60d9424a4664a417dce0b767

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

polymorphic associationに対してreflection.klassを取得しようとした場合にArgumentErrorをraiseするよう修正した、Merge pull request #31895 from kamipo/do_not_attempt_to_find_inverse_…の対応で、合わせてklass._reflect_on_associationNameErrorが起きた際に、そのエラーを無視するよう修正したのですが、そのNameErrorが起きた際に無視する、という挙動に依存しているテストがActive Recordのテスト内に多数あった為、NameErrorについては無視するよう処理を戻しています。


Update test to reflect direct upload header changes

activestorage/test/controllers/direct_uploads_controller_test.rbの修正です。

先のGoogle Cloud Storageにdirect uploadする際にcontent typeを指定しないよう修正した対応が、テストの修正が漏れていたので修正しています。


add private: true option for ActiveSupport delegate

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

delegateメソッドに、delegateしたメソッドの可視性をprivateとして扱うかどうかを指定する為のprivateオプションを追加しています。

class User < ActiveRecord::Base
  has_one :profile
  delegate :first_name, to: :profile
  delegate :date_of_birth, :religion, to: :profile, private: true

  def age
    Date.today.year - date_of_birth.year
  end
end

User.new.age # 2
User.new.first_name # Tomas
User.new.date_of_birth # NoMethodError: private method `date_of_birth' called for #<User:0x00000008221340>
User.new.religion # NoMethodError: private method `religion' called for #<User:0x00000008221340>

上記例だと、first_nameはアクセスできるのですが、privateオプションが指定されているdate_of_birth、及び、religionは可視性がprivateになる為、アクセスしようとするとNoMethodErrorになるようになっています。


Clear Blob's type before sending it

activestorage/app/javascript/activestorage/blob_upload.jsの修正です。

direct uploadでblobを送信する前にblob typeをクリアーするよう修正しています。

古いバージョンのChromeでBlob typeから取得したcontent type headerを勝手に追加する、という挙動が確認されたので、それを避ける為クリアーするようにした、ようです。


Remove extra changelog added by #31944

activesupport/CHANGELOG.mdの修正です。

add private: true option for ActiveSupport delegateの対応の際に関係ないエントリーまでCHANGELOGに追加されてしまったのを削除しています。


Change translation key of submit_tag from module_name_class_name to module_name/class_name

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

submit tagのvalueを生成する際に、i18n_keyを使用するよう修正しています。

元々はi18n_keyを使わずobject_nameを使用してvalueを生成していたのですが、それだとnamespaceの区切りに/が使えない(e.g. blog/post)為、i18n_keyを使うよう修正しています。


Merge pull request #32115 from avneetmalhotra/routing_bound_parameters_guide_fix

rails guideのRails Routing from the Outside Inの修正です。

Bound Parametersの項、exampleコードでtoオプションに指定する値に誤りがあったのを修正しています。


[ci skip]Change requring order of files in doc

rails guideのThe Rails Initialization Processの修正です。

Loading Railsの項に記載されているrailties/lib/rails/all.rbの内容が実際の内容と異なっていたのを修正しています。


Merge pull request #31189 from tgxworld/raise_error_when_advisory_lock_is_not_releases

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

migrationでadvisory lockのリリースに失敗した場合に、その状況がわかるエラーメッセージをraiseするよう修正しています。


add :nodoc: to ActionView::Helpers::FormBuilder#emitted_hidden_id?

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

内部用APIActionView::Helpers::FormBuilder#emitted_hidden_id?メソッドに:nodoc:の指定を追加しています。


Merge pull request #32005 from maschwenk/ar-distinct-order-count-regression

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

eager load + orderに任意のカラムを指定 + distinct + count or sizeを指定した場合に正しく値が取得出来ないバグがあったのを修正しています。


Merge pull request #28270 from mmangino/dont_ignore_seralization_options

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

serializationのincludesオプションに複数のHash(e.g. serializable_hash(include: [address: { only: "street" }, friends: { only: "name" }]))を指定した場合に、最初のHashに紐づく値しか取得されなかったのを、すべての値が取得されるよう修正しています。

rails commit log流し読み(2018/02/26)

2018/02/26分のコミットです。

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

activerecord/CHANGELOG.md


Remove native Array#sum and Enumerable#sum detection (#32102)

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

Array#sum、及び、Enumerable#sumが定義されているかのチェック処理を削除しています。

masterはRuby 2.4.1のみをサポートしており、上記メソッドは必ず定義されている為。


Association creation and finding should work consistently (#32048)

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

associationの作成及び取得処理でstore_full_sti_classの設定が無視されていたのを、store_full_sti_classの設定を反映するよう修正しています。

元々eager loadingやpreloadingではstore_full_sti_classの設定を使用するようになっており、挙動を合わせる為。


Merge pull request #31895 from kamipo/do_not_attempt_to_find_inverse_of_polymorphic

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

polymorphic associationに対してreflection.klassを取得しようとした場合に、ArgumentErrorをraiseするよう修正しています。

Rails 5.2.0.rc1でpolymorphic associationのcreate処理でエラーになる、というリグレッションが発生しました。これは色々な要因による複合条件で発生したリグレッションらしいのですが、そもそも取得出来るはずのないklassが取得出来てしまっていたのが根本的な原因だろう、という事で、polymorphic associationについてはklassが取得出来ないよう対応しています。


Active Model: Use private attr_reader

Active Modelの修正です。

attr_readerの可視性がprotectedになっていたのをprivateに修正しています。

Ruby 2.2以下でprivate attribute?のwarningが出てしまう為protectedにしていたのですが、masterでサポートしているバージョンは2.3以上になった為、privateに修正しています。


Remove changelogs for Rails 6.0 since they were backported to 5-2-stable

各CHANGELOから5.2にバックポートされたエントリーを削除しています。


Fix "NameError: uninitialized constant Categorization::Category"

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

不足していたmodels/categoryのrequireを追加しています。

rails commit log流し読み(2018/02/25)

2018/02/25分のコミットです。

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


Support varying ICO files

activestorage/app/models/active_storage/variant.rbactivestorage/lib/active_storage/engine.rbの修正です。

variantでサポートするcontent typeの一覧にimage/vnd.microsoft.iconを追加しています。


Support for automatic nonce generation was backported to 5.2

actionpack/CHANGELOG.mdの修正です。

nonceを自動生成する対応についてのエントリーを削除しています。5.2にバックポート済みで、6.0のnew featureでは無い為。


Merge pull request #31720 from grantbdev/update_default_hsts_max_age

actionpack/lib/action_dispatch/middleware/ssl.rbの修正です。

HSTS max-ageのデフォルトを180 daysから1 yearに修正しています。 max-ageは少なくとも1年以上である必要がある、とRFCに定義されている為、との事です。

参考:HSTS Preload List Submission


Use lazy load hook to configure ActiveStorage::Blob

activestorage/app/models/active_storage/blob.rbactivestorage/lib/active_storage/engine.rbの修正です。

Active Storageのserivceの設定行うのにto_prepare callbackを使用していたのを、lazy load hookを使用するよう修正しています。

to_prepareはinitialization処理中に実行される為、initialization処理中に、ActiveStorage::Blob及びActive Storageで使用しているActiveRecord::Baseがloadされてしまっていました。

initialization中にコンポーネントがloadされてしまうと、initializationでそれらのコンポーネントのconfigを変更した場合に正しく反映されない可能性がある為、initialization処理でloadされないようlazy load hookを使用するようにしています。

rails commit log流し読み(2018/02/24)

2018/02/24分のコミットです。

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

activesupport/CHANGELOG.md


Caching: MemCache and Redis stores use local cache for multi-reads

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

MemCache及びRedis storeでread_multifetch_multiメソッドを使用した際に、まずin-memory cacheから値を取得するよう修正しています。そちらの方がバックエンドから取得するより高速な為。


Improve generated file app/assets/javascripts/application.js of plugin

railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js.ttの修正です。

rails plugin用のjavascripts.jsrails-ujsをrequireするよう修正しています。


Merge pull request #32093 from jfragoulis/correct-method-documentation

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

ActiveSupport::Deprecation.behavior=メソッドのdoc内のexampleコードで、引数にブロックを指定した場合にブロックに渡ってくる引数の数が実際の数と異なっていたのを修正しています。


Correctly set content_security_policy_nonce_generator

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

content_security_policy_nonce_generatorにblockを指定するexampleで、blockに渡される引数の数が不足していたのを修正しています。


[ci skip] Spell out the full variable in generated code.

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

content_security_policy_nonce_generatorにblockを指定するexampleで、blockに渡される引数名をreq -> requestに修正しています。

rails commit log流し読み(2018/02/23)

2018/02/23分のコミットです。

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

actionpack/CHANGELOG.md

activejob/CHANGELOG.md


Merge pull request #32018 from rails/add-nonce-support-to-csp

Action Pack、Action Viewの修正です。

Rails UJSにCSPのnonce-sourceの自動生成処理を追加しています。

CSPには、nonce-sourceというホワイトリストの仕組みがあります。これは、CSPヘッダに指定されているnonceの値と、scriptタグに指定されたnonce属性の値が一致した場合、CSPでJavaScriptの実行が制限されていても、インラインでのJavaScriptでの実行を許可する、というものです。多分。

この対応により、CSPにunsafe-inlineが指定されていてもRails UJSのJavaScriptはインラインで実行されるようになっています。

また、javascript_tagメソッドにnonceオプションを追加し、ユーザが任意に実行したいインラインのJavaScriptも実行出来るようになっています。

<%= javascript_tag nonce: true do %>
  alert('Hello, World!');
<% end %>

なお、上記仕組みを使用する為には、csp_meta_tagメソッドでcsp用のmeta tagを生成する必要があります。新規に作成したアプリではapplication.html.erbではcsp_meta_tagメソッドを呼ぶよう指定されていますが、アップグレードしたアプリでは自分で指定を追加する必要があります。

参考:


Merge pull request #32085 from rails/add-timezone-support-to-activejob

Active Jobの修正です。

Active Jobにtimezoneのサポートを追加しています。

jobをenqueueする際に現在のtimezoneを含むよう対応、及び、jobをrestoreした際にそのtimezoneの値を使用するようにしています。jobにtimezoneが含まれていない場合は現在のtimezoneが使われます。localeと同じアプローチです。


Revert "Reject empty database yamls"

database configurationをロードした際に、databaseの設定が無いセクションを削除するよう修正した、Reject empty database yamlsをrevertしています。

上記コミットは、Reject empty database yamlsから続いていた対応で、database用のconfigをrake taskでロードした際に行っていたdefaultセクションの場合のケアを削除する為に追加されました。

ただ、configを最初にロードした際にdefaultセクションを削除する事は出来ない(configファイルに3階層目を指定した場合にdefaultは必要)為、revertしています。


Revert "Merge pull request #32075 from eileencodes/delete-default-configuration"

database configurationをロードした際に、defaultセクションを削除するよう修正したい、Delete default configurationをrevertしています。理由は同上。


Remove passing extra arguments to ActiveJob Callbacks

Active Jobの修正です。

around_enqueuearound_performから使用していない第三引数を削除しています。


Comment require "active_storage/engine" in bin/rails of plugin if --skip-active-storage

railties/lib/rails/generators/rails/plugin/templates/bin/rails.ttの修正です。

--skip-active-storageオプションを指定してrails pluginを生成した際に、active_storage/engineを読み込まないよう修正しています。


Improve generated file app/views/application.html.erb of plugin

railties/lib/rails/generators/rails/plugin/templates/app/views/layouts/%25namespaced_name%25/application.html.erb.ttの修正です。

--skip-javascriptオプションを指定してrails pluginを生成した際に、application.html.erbjavascript_include_tagを呼ばないよう修正しています。合わせて、csp_meta_tagメソッドの呼び出しを追加しています。


Update rubocop to the latest version

Gemfile.lockの修正です。

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


Use rubocop-0-52 channel

.codeclimate.ymlの修正です。

codeclimateで使用するrubocopのバージョンも0.52に更新しています。


Use private attr_reader

Active Recordの修正です。

attr_readerの可視性がprotectedになっていたのをprivateに修正しています。

Ruby 2.2以下でprivate attribute?のwarningが出てしまう為protectedにしていたのですが、masterでサポートしているバージョンは2.3以上になった為、privateに修正しています。


PostgreSQL: Treat infinite values in date like datetime consistently

Active Recordの修正です。

date型にinfinity / -infinityを指定した場合に、正しく扱えて無かった(Float::INFINITYマッピングされて無かった)のを、datetime同様に正しく扱えるよう修正しています。


PostgreSQL: Allow BC dates like datetime consistently

activemodel/lib/active_model/type/date.rbactiverecord/lib/active_record/connection_adapters/postgresql/oid/date.rbの修正です。

Dateでyearに0を指定した場合、1 BCとみなすよう修正しています。

元々DateTimeでは上記挙動になっており、挙動を合わせる為修正しています。

PostgreSQLではtimestampdate4713 BC以降の値をサポートしているんですね。知らなかった。

参考:PostgreSQL: Documentation: 10: 8.5. Date/Time Types


More exercise range predicate builder

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

open-ended rangeを指定した場合、及び、string columnにnumeric rangeを使用した場合のテストを追加しています。

rails commit log流し読み(2018/02/22)

2018/02/22分のコミットです。

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


Delete default configuration

activerecord/lib/active_record/tasks/database_tasks.rbrailties/lib/rails/application/configuration.rbの修正です。

database configurationをロードした際に、defaultセクションを削除するよう修正しています。

元々はそのまま保持していたのですが、DatabaseTasksでconfigurationを参照する際にdefaultセクションの場合は処理をスキップする、という処理が入っていた為、ロード時に削除し、チェックは行わないすむよう修正しています。


Call YAML.load correctly

activerecord/lib/active_record/railties/databases.rakeactivesupport/lib/active_support/xml_mini.rbの修正です。

クラスメソッドを呼び出すのに::を使用していたのを、.を使用するよう修正しています。

-        if data = YAML::load(ERB.new(IO.read(file)).result)
+        if data = YAML.load(ERB.new(IO.read(file)).result)

Do not add routes when actions are not specified

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

controller generatorでactionが指定されていない場合は、routesにnamespaceを追加しないよう修正しています。Rails 5.1までと挙動を合わせる為。


We should call methods with .method_name not ::method_name.

他にもクラスメソッドを呼び出すのに::を使用している箇所があったのを、.を使用するよう修正しています。


Add cop for preferring 'Foo.method' over 'Foo::method'

.rubocop.ymlStyle/ColonMethodCall copを追加、及び、各ファイルにcopを適応しています。


Reject empty database yamls

railties/lib/rails/application/configuration.rbの修正です。

database configurationをロードした際に、databaseの設定が無いセクションを削除するよう修正しています。

Delete default configurationdefaultセクションを削除するよう修正したのですが、それだとdefaultセクションにdatabaseの設定があった場合に問題になる(YAMLのアンカーを使っている場合)為、databaseの設定が無い箇所を削除する修正しています。


Properly escape column name embedded into regexp

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

test_default_values_are_deeply_duppedでqueryにquoted_idが含まれているか確認する際に、quoted_idRegexp.escapeで囲むよう修正しています。

-    assert_match(/SELECT #{quoted_id}.* FROM developers/, query)
+    assert_match(/SELECT #{Regexp.escape(quoted_id)}.* FROM developers/, query)

SQLServerAdapterではカラム名に中括弧を使うようになっており(e.g.[id])、括弧をエスケープしないと正しくマッチしない為。