2016年5月24日火曜日

New functions and changes in Rails 5

Introduction

Before the release of Ruby 2.3, the first beta version of Ruby on Rails version 5.0 series (following Rails 5) has been released.

Rails 5, along with the introduction of new features for the JSON API server and WebSocket server, it has a big change internally is added to work with Ruby 2.2.2 or higher. In addition, the model is or is inherited from ApplicationRecord, have been made a big hand also to the basic part such or to be able to run the Rake tasks in the rails command.

In this article, based on the Rails project of Issues and Pull Requests of the history of GitHub, make the introduction of major new features, changes in Rails 5.

New Function

Rails API

Instead of ActionController :: Base by inheriting the ActionController :: API on the controller, it is now possible to build a lightweight Rails application for the JSON API server.
If you want to completely create a Rails application of only API, specify the --api option in the rails new.

$ rails new my_api --api
This, will be made the following.

1. will be a minimum of middleware load to move the API server.
2. ApplicationController is, will now inherit the ActionController :: API.
3. in the generator, does not take place the generation of view and assets.

If you are an existing Rails application only to the API, please click here to reference.

Action Cable

By using the Action Cable, it is now possible to easily add the functionality of the WebSocket that enables real-time two-way communication to the Rails application. The Action Cable, has been included in both the server and client functionality.

On the server side, perform the implementation using the class, such as ApplicationCable :: Connection and ApplicationCable :: Channel, on the client side, you call the AppearanceChannel # subscribed method of server-side by App.cable.subscriptions.create of CoffeeScript (JavaScript) .

You can generate code for both the server and the client in the generator. The following is an example to generate a channel of chat.

$ rails generate channel chat 
Please refer to here as a reference for a detailed code examples.

The rake task so that it can be run from the rails command

Various tasks to be performed in the rake command can now be run on rails command.
For example, the migration of DB is rails db: migrate, confirmation of routing is able to perform in the rails routes.

Turbolinks 5

It becomes a data-turbolinks-permanent to be held between pages by attaching to the DOM element, because it does not require the initialization of the state, now runs faster.
Such as the sidebar, in the case of fixed elements between the page, grant the data-turbolinks-permanent, is not element held in between the pages, it seems may put a daa-turbolinks-temporary.
id="nav" data-turbolinks-permanent>
id="footer" data-turbolinks-temporary>

Support of Sprockets 3

Rails up to 4 had to specify whether to pre-compile any assets in the config / initializers / assets.rb, but specified in manifest.js in Rails 5 in the app / assets / config / directory.

In the initial state of the application, manifest.js is as below.
//= link_tree ../images
//= link_directory ../javascripts .js
//= link_directory ../stylesheets .css 
(In the following reference page, but has become a Sprockets 4, is currently still Sprockets 3)

ActiveRecord::Attributes

By specifying the attributes in the model of the attribute, or to get the attributes of the model in SQL, you can now customize the way or pass to where the method of ActiveRecord :: Relation. For example, an attribute on the DB, which is defined in the decimal type as follows:
create_table :store_listings, force: true do |t|
  t.decimal :price_in_cents
end
In attribute, by specifying the integer, it can be converted to an integer.
class StoreListing < ActiveRecord::Base
  attribute :price_in_cents, :integer
end
The before and after that convert attribute will vary as follows.
# before
store_listing.price_in_cents
=> BigDecimal.new(10.1)
# after
store_listing.price_in_cents
=> 10 
Please refer to the following reference for more information.

Queries related methods add (#or, #left_outer_joins, #left_joins)

ActiveRecord :: Relation can specify OR conditions in SQL to #or and #left_outer_joins method of performing the outer join has been added.
Post.where('id = 1').or(Post.where('id = 2'))
=> SELECT * FROM posts WHERE (id = 1) OR (id = 2)
User.left_outer_joins(:posts)
=> SELECT "users".* FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" = "users"."id"
In addition, #left_joins alias of # left_outer_joins has also been added.

Added #pluck and #without to Enumerable module

Methods of behavior similar to #pluck method to arrange the column for a particular record now can also be used in an array of hash.
[{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pluck(:name)
=> ["David", "Rafael", "Aaron"]
In addition, #without method except for the specific elements from in the array has been added.
people = ["David", "Rafael", "Aaron", "Todd"]
people.without "Aaron", "Todd"
=> ["David", "Rafael"]

touch option is added to the #save of 

touch to the record at the time stored in the options of #save methods: by passing a false, you can now so that it does not update the time stamp.
In the following example, even after you update the data of model objects that article, the value of updated_at will be the same.
updated_at = article
artile.save!(touch: false)
article.update_at == updated_at
=> true

It added ActiveRecord :: Relation # in_batches method

ActiveRecord # find_in_bathces the number of data to perform the processing for a large model is passing an array to the block to pass the record, ActiveRecord # in_bathces method, you can now pass the ActiveRecord :: Relation to block. By passing of the options, you can change the size of the batch. (Default is 1000)
Person.in_batches.each_record(&:party_all_night!)
Person.in_batches.update_all(awesome: true)
Person.in_batches.delete_all
Person.in_batches.each do |relation|
  relation.delete_all
  sleep 10 # Throttles the delete queries
end

change point

belongs_toの参照先がnilの場合はバリデーションエラーに

Rails 4以前の挙動に戻すには、belongs_toのオプションでoptional: trueを指定する必要があるそうです。

ActiveRecordのモデルがApplicationRecordから継承されるように

Rails 5で新しくアプリケーションを作成した場合、app/models/application_record.rbが以下のように作成され、他のモデルを生成する際も、ActiveRecord::Baseではなく、ApplicationRecordから継承を行うようになりました。
class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
end
これまでは、アプリケーションのモデル全体にある機能を追加したい場合は、ActiveRecord::Baseにモンキーパッチを行うか、モジュールをincludeする必要がありましたが、Rails 5以降では、ApplicationRecordにメソッドなどを追加すればよいことになります。

ActiveJobのジョブもApplicationJobから継承されるように

ActiveJobに関しても同じく、各ジョブはActiveJob::Baseではなく、以下のapp/jobs/application_job.rbで記述される、ApplicationJobから継承を行うようになりました。
class ApplicationJob < ActiveJob::Base
end

ActionController::Parametersが、ハッシュから継承されなくなった

これまでのParametersが、ActiveSupport::HashWithIndifferentAccessから継承されていてEnumerableモジュールの各メソッドで許可されていないパラメータを操作される危険性があったので変更したとのことです。(既存のハッシュなどのメソッドを使用している場合は、アップグレードの際に注意が必要です。)

alias_method_chainが非推奨に

Rails 5では、Ruby 2.2.2以上を使用するので、ActiveSupportのalias_method_chainではなくRubyのModule#prependを使用するようになっています。

Summary

Rails 5 is, spread the width of the application than ever before, such as Rails API and Action Cable, seems to various queries related methods has become a hand reach version to itchy part because it was added. Already since the beta version has been released, or try the new features, why not or to go to upgrade an existing Rails 4 applications.

0 件のコメント:

コメントを投稿