Table of contents
- Switch to Rails 3.0
- Rails 3 requires Ruby 1.8.7+
- Application object in Rails
script/*
replaced by script/rails
- Dependencies and
config.gem
- Transition process
- Creating a Rails 3.0 Application
- Inclusion of gems
- Life on the brink
- Architectural changes
- Recharge Railties
- All components of the Rails core are now independent.
- Abstraction Active Model
- Abstraction controllers
- Arel Integration
- Extract Mail
- Documentation
- Internationalization
- Railties
- Action pack
- Abstract controller
- Action controller
- Action Dispatch
- Action view
- Active Model
- Abstraction ORM and interface with Action Pack
- Validations
- Active record
- Query interface
- Enhancements
- Patches and obsolete methods
- Active Resource
- Active support
- Action Mailers
- About creators
Introduction
Ruby on Rails 3.0 is out! He will cook dinner for you and fill the washing machine with laundry. You will still wonder how you used to live without it. These are the best rails we have ever done!
Well, seriously speaking, it was a really great thing. With the arrival of the creators of Merb in the team, we implemented their best ideas, and, moreover, focused on the agnosticism of the framework, simplifying and accelerating the code, and also added a handful of new APIs. If you switch to Rails 3.0 from Merb'a 1.x, you will most likely be familiar with a lot. And you will definitely fall in love with Rails 3.0 by upgrading from any version 2.x.
But even if you don’t care about the internal cleaning of the code, you’ll still feel the full taste of Rails 3.0. We have prepared a whole bunch of new features and updated APIs. It's time to become a Rails developer. Here are the main changes:
- Brand new RESTful-style router;
- New API for Action Mailer, created in the image of the Action Controller (now without hell of sending messages from several parts);
- Language for creating a query chain in Active Record, built on the basis of relational algebra;
- Unobtrusive Javascript helpers with drivers for Prototype, jQuery and, in the near future, other frameworks (end of inline JS);
- Explicit dependency management with Bundler.
In addition to all this, we tried our best to isolate outdated APIs by supplying the corresponding components with special messages. Those. in order to upgrade to Rails 3.0 now, you do not need to rewrite all existing code to fit all the innovations.
')
These release notes cover only the major innovations, but not every bugfix or minor change. Rails 3.0 consists of about 4,000 commits from over 1,600 authors! If you need to know everything in detail, pay attention to the
list of all commits .
1. Switch to Rails 3
As usual, when upgrading to a new version, it’s best to have your code covered as much as possible with tests. And, for a start, you'd better upgrade to 2.3.5 to make sure that your application is working properly even before switching to Rails 3.0.
1.1 Rails 3.0 requires Ruby 1.8.7+
Rails 3.0 requires Ruby 1.8.7 or higher. Support for previous versions has been officially discontinued, so we recommend that you upgrade to the new version of Ruby as soon as possible. In addition, Rails is compatible with Ruby version 1.9.2.
Note that in Ruby 1.8.7 p248 and p249 there are marshaling bugs that crash Rails 3.0. In Ruby Enterprise Edition, this has been fixed since version 1.8.7-2010.02. As for 1.9, Ruby 1.9.1 also cannot be used. in Rails 3.0, it causes segmentation errors (segfaults). So, if you want to use Rails 3.0 Ruby 1.9, jump immediately to 1.9.2.
1.2 Application Object
As part of working to support multiple Rails applications running in the same process, Rails 3.0 introduces a new concept that involves using the
Application
object. This object contains all of your application-specific configuration settings and, by its nature, is very similar to the contents of config / environment.rb from previous versions of Rails.
Now each Rails application has a special
Application
object. This object is defined in the config / application.rb file. If you need to update an existing application to a new version of Rails, you need to create this file manually, and copy the necessary information into it from config / environment.rb.
1.3 script/*
replaced by script/rails
New script / rails now replaces all scripts in the corresponding folder. But you do not need to contact script / rails directly - just run the
rails
command from the root of the application, which, in the context of your application, executes the specified script. For example:
rails console # => ./script/console
rails g scaffold post title:string # => ./script/generate scaffold post title:string
The
rails –help
team will kindly provide the entire list of available options.
1.4 Dependencies and config.gem
The
config.gem
method went into non-existence in favor of the
bundler
'a and
Gemfile
' a (see “Turning on gems” below)
1.5 Transition Process
To automate and simplify the transition process, a special plugin was created -
Rails Upgrade .
Just install the plugin and run
$ rake rails:upgrade:check
to find out which of the existing parts of your program need to be updated (with links to information about how and what to upgrade). Also in the plugin there is a task for generating a
Gemfile
based on existing calls in
config.gem
and a task for generating a new file with routes based on the old one. To download the plugin, simply do the following -
$ script/plugin install git://github.com/rails/rails_upgrade.git
.
You can learn by example how this all works, by clicking on the link
Rails Upgrade now. Official Plugin .
On the other hand, if you need more help, you can always contact the people on the IRC channel or in the
rubyonrails-talk mailing list, who probably do the same thing as you, and maybe even face the same problems. When you finally succeed - do not forget to write on your blog to share your experience with others!
More information -
The Path to Rails 3: Approaching the upgrade .
2. Creating a new Rails application
The sequence at the moment looks like this:
$ gem install rails --version 3.0.0
$ rails myapp
$ cd myapp
2.1 Turning on gems
Rails now uses
Gemfile
to know which plugins are required to run your application. To read and work with this file, there is a new bundle gem, which puts all the necessary gems in the
vendor
directory, thereby isolating your application from system gems.
Additional information -
Using bundler .
2.2 Life on the brink
Now, thanks to the
bundler
and
Gemfile
, in order to “freeze” your application, just run the special command
bundle
-ra - goodbye
rake freeze
! ..
Well, if you use code from the Rails repository master branch, then to create an application, simply pass the -
--dev
flag:
$ rails myapp —edge
3. Architectural changes in Rails
The Rails architecture has undergone 6 major changes.
3.1 Recharging Railties
Railties have been updated to provide a robust API for writing plugins to any components of the framework. Generators and binders have also been completely rewritten, which gives developers the opportunity to move to an incomparably different level of elegance of their use.
3.2 All Rails core components are now independent.
Together with the merging of Merb and Rails, one of the main tasks was to get rid of the strong connection between the components of the Rails core. This goal has been achieved, and now all of the key Rails components use a single API that you can use to develop plug-ins.
This means that any plugin or replacement of any component of the kernel (using, for example, DataMapper or Sequel) has access to the same functionality as the kernel, with the possibility of its expansion and improvement.
More information -
The Great Decoupling3.3 Abstraction Active Model
Part of the work on the separation of components was the extraction of all bindings to the Active Record from the Action Pack. Now that this is completed, for any new ORM plugin, in order to work correctly with the Action Pack, all the Active Model interfaces need to be implemented.
Additional information -
ActiveModel: let any Ruby object feel like ActiveRecord3.4 Abstract controller
Another significant part in the work on the separation of components in the core was the creation of a base superclass isolated from HTTP in order to render templates and so on. Creating an Abstract Controller made it possible to significantly simplify the Action Controller and Action Mailer by extracting the code common to both in Abstract Controller.
More information -
Rails Edge Architecture .
3.5 Arel Integration
Arel (or Active Relation) was taken as the foundation for Active Record and is henceforth one of the dependencies of a Rails application. Arel introduces a special SQL abstraction, thereby simplifying Active Record and providing a foundation for implementing relational functions in Active Record.
Additional information -
Why I wrote Arel .
3.6 Retrieving Mail
From the day of its creation, Action Mailer was constantly hung up with dubious patches, pre-parsers and, in addition to combining with TMail, got agents to send and receive mail. In version 3.0, all the functionality related to e-mail was abstractly rendered in the
Mail gem. This, again, reduced the amount of duplicate code and helped to separate Action Mailer from the email parser.
Additional information -
New Action Mailer API in Rails 3 .
4. Documentation
Documentation for all API changes is in the process of being updated. In addition to this,
the Rails Edge guides are also updated to reflect all the changes in Rails 3.0. However,
guides.rubyonrails.org manuals will only correspond to the latest stable version (i.e. version 2.3.5, up to the final release 3.0).
More information -
Rails Documentation Projects .
5. Internationalization
In Rails 3, a significant amount of work has been done on supporting internationalization. The latest version of the
i18n heme is included and carries a significant optimization of the speed of work.
- I18n in every home - now, if desired, you can embed l18n into any object by adding the ActiveModel :: Translation and ActiveModel :: Validations modules to it. Additionally, translation support has been added for errors.messages.
- Attributes can now set the default language.
- The form tags automatically determine the object's status (Create or Update), tighten the correct translation language.
- The Label tag with l18n now works correctly - just pass the attribute name to it.
More information -
Rails 3 I18n changes .
6. Railties
Together with the separation of the main components within Rails, Railities have been thoroughly redesigned in order to facilitate the interaction between frameworks, engines and plugins, making it as painless and flexible as possible:
- Each application is now assigned its own namespace (for example, the application is launched as follows:
YourAppName.boot
), which makes interaction between applications much easier. - Now you can turn to
Rails.config
, where there is a huge variety of configuration options for your application. - Everything inside the
Rails.root/app
now automatically added to the load path
, so now you can, say, add the file app/observers/user_observer.rb
, and Rails will simply load it.
At the beginning of the application generation, you can now use several new flags, including flags that allow you to skip the installation of components such as test-unit, Active Record, Prototype and Git. In addition, thanks to the new
-dev
flag, when installing the application, the
Gemfile
is taken from the current Rails repository. See
rails –help
for help.
Generators of various Railities have been given a huge amount of attention. In short:
- Generators have been rewritten from scratch and are no longer backward compatible.
- The template and generator APIs were connected together.
- Generators are no longer loaded from the special path (load path), but simply loaded from the load path (Ruby load path), so the
script/generate foo
call will do the same as generators/foo_generator
- Now you can easily connect any new template engine, ORM or testing framework to the generator.
- In the new generators, you can easily rewrite the original templates by simply putting the desired file in
RAILS_ROOT/lib/templates
. Rails::Generators::TestCase
, thanks to which you can create and test your own generators.
In addition, the generated view also received some improvements:
- In generated views,
div
tags are now used instead of p
. - When generating forms using scaffold, instead of duplicating the code in the edit and new views, the partial with the
_form
now used - When generating forms using scaffold,
f.submit
is now used, which returns “Create ModelName” or “Update ModelName”, depending on the state in which the object came
Finally, improvements have touched and rake tasks:
- The
rake db:forward
task has been added, thanks to which you can now rotate the migrations forward individually or in groups. - The task of
rake routes CONTROLLER=x
been added, which now allows you to view routes for one specific controller.
Found obsolete:
RAILS_ROOT
in favor of Rails.root
,RAILS_ENV
in favor of Rails.env
,RAILS_DEFAULT_LOGGER
in favor of Rails.logger
.
PLUGIN/rails/tasks
and
PLUGIN/tasks
no longer loaded — all tasks must be in the
PLUGIN/lib/tasks
directory.
Additional information :
7. Action Pack
Action Pack has undergone significant internal and external changes.
7.1 Abstract Controller
From the
Action Controller
'a to
Abstract Controller
, in the form of modules, the main parts were taken out, which can now be used to render templates,
partial
' s,
helper
's, internationalization, logging and any other part of the “request-response” cycle. Thanks to this abstraction,
ActionMailer::Base
now simply inherited from
Abstract Controller
'a, being, as a wrapper, a wrapper over Rails DSL in the form of the Mail heme.
The introduction in the
Abstract Controller
all that was possible, has greatly simplified the
Action Controller
. However, it should be borne in mind that programmers will not be able to directly access
Abstract Controller
's, this is not an API.
More information -
Rails Edge Architecture .
7.2 Action Controller
- The
application_controller.rb
now protect_from_forgery
now set as default. cookie_verifier_secret
been deprecated. Now, instead you should refer to Rails.application.config.cookie_secret
, and its implementation is now in a separate file initializers/cookie_verification_secret.rb
session_store
been moved to initializers/session_store.rb
cookies.secure
now allows you to set encrypted values ​​in the cookie hash: cookie.secure[:key] => value
cookies.permanent
now allows you to set constant values ​​in the cookie hash: cookie.permanent[:key] => value
, which causes an exception if the verification was unsuccessful- Now you can send
notice => ' flash-'
or :alert => '- '
to call format
in the respond_to
. Hash flash[]
still in service respond_with
was added to the controllers, thereby simplifying outdated format
blocksActionController::Responder
been added, with which you can flexibly generate responses (responses)
Found obsolete:
filter_parameter_logging
in favor of config.filter_parameters << :password
Additional Information:
7.3 Action Dispatch
Introduced in Rails 3.0, this new component is designed to greatly simplify routing.
- after a strong cleaning and rewriting of routing, now the
router
is rack_mount
over Rails DLS, i.e. in fact, it is now a separate small application. - Routes declared in the application are now in the application namespace. Those. now instead of:
ActionController::Routing::Routes.draw do
map.resources :posts
end
Need to write:AppName::Application.routes do
resources :posts
end
- added
match
method, so now you can hang a Rack application on a suitable (matched) route - added the method of
constraints
, giving the opportunity to protect their routes conditions - added the
scope
method, with which you can place routes in namespaces (for example, for different languages ​​or special actions). For example, the following code:
scope 'es' do
resources :projects, :path_names => { :edit => 'cambiar' }, :as => 'projeto'
end
will call the edit
method at /es/projeto/1/cambiar
root
method added as a shortcut to match '/', :to => path
- An optional segment can be passed to
match
. So, in match “/:controller(/:action(/:id))(.:format)”
, any text enclosed in brackets is optional - routes can be expressed as blocks, i.e. Now for example you can write
:home { match '/:action' }
It is important to remember that the outdated
map
commands are still in service, but with the advent of 3.1 they will disappear completely.
Found obsolete:
- the host for all non-REST applications (
/:controller/:action/:id
) was commented out :path_prefix
for routes is removed, but :name_prefix
now automatically adds "_" at the end of the passed value
Additional Information:
7.4 Action View
7.4.1 Unobtrusive JavaScript
Helpers underwent significant revisions in the Action View: hooks for Unobtrusive JavaScript (UJS) were introduced, and the old inline-AJAX teams have sunk into oblivion. Thus, in Rails, you can now use any UJS driver to implement UJS hooks in helpers.
This means that all previously existing
remote_
helpers
remote_
been removed from the rails, and are now in the special
Prototype Legacy Helper . Now, to access the UJS hooks, just pass
:remote => true
. So, for example:
form_for @post, :remote => true
will return:
form action="http://host.com" id="create-post" method="post" data-remote="true"
7.4.2 Block Helpers
form_for
such as
form_for
or
div_for
, which insert content from the block now use
<%=
:
<%= form_for @post do |f| %>
...
<% end %>
Your own helpers of this type will return the string and not add the output manually to the output buffer.
Other helpers, such as
cache
and
content_for
, have remained intact.
7.4.3 Other changes
- You no longer need to call
h(String)
to filter HTML - now all views are generated with default filtering. In order to pass an unfiltered string, you need to call raw(string)
. - Helpers now return HTML5 markup.
- The
label
helper now retrieves data from I18n with one parameter, i.e. f.label :name
will immediately return the translated :name
. - Select for I18n is now called as
:en.helpers.select
instead of :en.support.select
. - You no longer need to put a minus sign in the closing tag of the ERb-template in order to avoid the translation deadlines.
- The
grouped_collection_select
helper has been added to ActionView. - Added
content_for?
method content_for?
to check before rendering whether content exists. - By passing
:value => nil
for form helpers, you set the field value to nil
instead of using the default value. - Passing
:id => nil
for form helpers the attribute id
will not be generated. - By passing
:alt => nil
for the image_tag helper, you set the field value to nil
instead of using the default value.
8 Active Model
Active Model is a new component of Rails 3.0. Now, any ORM library can interact with Rails - you just need to implement the Active Model interface, which is only an abstract layer.
8.1 ORM Abstraction and Action Pack Interface
Part of the work of disrupting the core components of Rails was to extract all the links in Active Record from the Action Pack. Now that this is complete, any ORM library need only implement the Active Model interfaces in order to simply access Active Record.
Additional information -
Make Any Ruby Object Feel Like ActiveRecord8.2
Active Record Active Model, ORM .
validates :attribute, options_hash
.
options_hash
, :
:acceptance => Boolean
:confirmation => Boolean
:exclusion => { :in => Ennumerable }
:inclusion => { :in => Ennumerable }
:format => { :with => Regexp, :on => :create }
:length => { :maximum => Fixnum }
:numericality => Boolean
:presence => Boolean
:uniqueness => Boolean
: — ( ) .
-, ActiveModel. For example:
class TitleValidator < ActiveModel::EachValidator
Titles = ['Mr.', 'Mrs.', 'Dr.']
def validate_each(record, attribute, value)
unless Titles.include?(value)
record.errors[attribute] << 'must be a valid title'
end
end
end
class Person
include ActiveModel::Validations
attr_accessor :title
validates :title, :presence => true, :title => true
end
Active Record:
class Person < ActiveRecord::Base
validates :title, :presence => true, :title => true
end
Additional information :
9. Active Record
Active Record Rails 3 : Active Model, Arel, . API Rails 2.x , Rails 3.1 .
9.1
Active Record, Arel,
relation
. API Rails 3.1, Rails 3.2. , , :
where
— reletion, .. .select
— .group
— relation .having
— GROUP BY
SQL.joins
— relation'a .clause
— JOIN
SQL.includes
— , ralations.order
— relation .limit
— relation.lock
— .readonly
— « ».from
— relation'a .scope
— ( named_scope
) relation.with_scope
— with_exclusive_scope
, relation.default_scope
— relation'
Additional information :
9.2
:destroyed?
Active Record:inverse_of
,
9.3
, Active Record :
- SQLite 2 SQLite 3.
- MySQL.
- PostgreSQL
TIME_ZONE
— . - PostgreSQL.
table_name
.- , Oracle.
, :
named_scope
Active Record scope
scope
relation' :condition => {}
. : :since, lambda {|time| where(“created_at > ?”, time) }
save(false)
save(:validate => false)
- I18n Active Record
:en.activerecord.errors.template
:en.errors.template
model.errors.on
model.errors[]
validates_presence_of
:presence => true
ActiveRecord::Base.colorize_logging
and config.active_record.colorize_logging
are deemed obsolete in favor of Rails::Subscriber.colorize_logging
or config.colorize_logging
.
It should be noted that the last few months being developed so-called. State Machine is not included in Rails 3.0.10. Active Resourse
Active Resourse was also extracted in Active Model, which made it easy to use Active Resourse objects in the Action Pack.- Added validations thanks to Active Model.
- Added observing hooks.
- HTTP proxy support
- Added support for digest authentication.
- Model naming moved to Active Model.
- Active Resource attributes are changed to a random access hash.
- Added alias-methods
first
, last
and all
for the relevant scope. find_every
no longer returns an error ResourceNotFound
if nothing is found- Added
save!
, which returns ResourceInvalid
in case the object is notvalid?
. - In ActiveResource models added to the methods
update_attribute
and update_attributes
. - Now, for loading remote errors, Active Resours'a is
content-type
used format
instead. - For a schema block, it is used
instance_eval
. - Fixed
ActiveResource::ConnectionError#to_s
where @response
did not respond to #code or #message (...). - Added support for errors in JSON format.
- Work
load
with arrays of numbers is provided . - Answer 410 from a remote source, in case it was deleted, is now recognized correctly.
- In the Active Resouce option added SSL options.
- Setting the timeout for the connection now also affects
Net::HTTP
open_timeout
.
Found obsolete:save(false)
declared obsolete in favor save(:validate => false)
- Ruby 1.9.2:
URI.parse
.decode
11. Active Support
Active Support, Active Support , - . , Rails .
- ,
- Active Support TZInfo , Memchache Client Bundle : ,
gem bundle
- ActiveSupport::SafeBuffer
Array.uniq_by
Array.uniq_by!
- ,
TimeZone.seconds_to_utc_offset
ActiveSupport::Notifications
ActiveSupport.use_standard_json_time_format
true
ActiveSupport.escape_html_entities_in_json
true
Integer#multiple_of?
, — false
string.chars
string.mb_chars
ActiveSupport::OrderedHash
- YAML- SAX XmlMini, LibXML Nokogiri
Object#presence
, ( — nil
)String#exclude?
include?
to_i
DateTime
, Active Support
, to_yaml
DateTime
Enumerable#exclude?
Enumerable#include?
, !x.include?
- XSS
ActiveSupport::HashWithIndifferentAccess
Enumerable#sum
, :size
inspect
0
modelname
element
collection
String#to_time
String#to_datetime
- -,
:before
:after
, ActiveSupport::OrderedHash#to_a
( Hash#to_a
Ruby 1.9)MissingSourseFile
, LoadError
Class#class_attribute
, ,- -
ActiveRecord
DeprecatedCallbacks
, Ruby 1.8.7 Ruby 1.9:
Integer#even?
and Integer#odd?
String#each_char
String#start_with?
String#end_with?
(3rd person aliases still kept)String#bytesize
Object#tap
Symbol#to_proc
Object#instance_variable_defined?
Enumerable#none?
REXML Active Support, Ruby 1.8.7 . Active Support , , .
:
Object#remove_subclasses_of
, Object#subclasses_of
, Object#extend_with_included_modules_from
Object#extended_by
Class#subclasses
, Class#reachable?
, Class#remove_class
Regexp#number_of_captures
Regexp.unoptionalize
, Regexp.optionalize
, Regexp#number_of_captures
12. Action Mailer
TMail
Mail , Action Mailer API. , Action Mailer . , Action Mailer Abstract Controller'a, Mail gem. Action Mailer.
app/mailers
- email, API :
attachments
, headers
mail
- Action Mailer, Mail::Message,
deliver
respond_block
Action Contoller'e, . , Action Mailer ,- proc
format.mime_type
mail-, , - unit- mailer'
:charset
, :content_type
, :mime_version
, :implicit_parts_order
ActionMailer.default :key => value
create_method_name
deliver_method_name
— method_name
, Mail::Message
.ActionMailer.deliver(message)
, message.deliver
.template_root
— Proc- format.mime_type
mail
.body
, instance- ( body {:ivar => value}
), instance- — .app/models
app/mailer
.
Additional information :
13.
, Rails 3. !
Ps. , .PPS. maratk !