railties 3.1.1 → 3.1.2.rc1
Sign up to get free protection for your applications and to get access to all the features.
- data/CHANGELOG.md +2382 -0
- data/guides/output/2_2_release_notes.html +565 -0
- data/guides/output/2_3_release_notes.html +713 -0
- data/guides/output/3_0_release_notes.html +652 -0
- data/guides/output/3_1_release_notes.html +670 -0
- data/guides/output/action_controller_overview.html +925 -0
- data/guides/output/action_mailer_basics.html +658 -0
- data/guides/output/action_view_overview.html +1471 -0
- data/guides/output/active_model_basics.html +349 -0
- data/guides/output/active_record_basics.html +364 -0
- data/guides/output/active_record_querying.html +1272 -0
- data/guides/output/active_record_validations_callbacks.html +1292 -0
- data/guides/output/active_resource_basics.html +252 -0
- data/guides/output/active_support_core_extensions.html +3374 -0
- data/guides/output/ajax_on_rails.html +412 -0
- data/guides/output/api_documentation_guidelines.html +317 -0
- data/guides/output/asset_pipeline.html +691 -0
- data/guides/output/association_basics.html +1742 -0
- data/guides/output/caching_with_rails.html +533 -0
- data/guides/output/command_line.html +662 -0
- data/guides/output/configuring.html +811 -0
- data/guides/output/contribute.html +216 -0
- data/guides/output/contributing_to_ruby_on_rails.html +465 -0
- data/guides/output/credits.html +210 -0
- data/guides/output/debugging_rails_applications.html +791 -0
- data/guides/output/engines.html +673 -0
- data/guides/output/form_helpers.html +850 -0
- data/guides/output/generators.html +725 -0
- data/guides/output/getting_started.html +1980 -0
- data/guides/output/i18n.html +1054 -0
- data/guides/output/images/belongs_to.png +0 -0
- data/guides/output/images/book_icon.gif +0 -0
- data/guides/output/images/bullet.gif +0 -0
- data/guides/output/images/challenge.png +0 -0
- data/guides/output/images/chapters_icon.gif +0 -0
- data/guides/output/images/check_bullet.gif +0 -0
- data/guides/output/images/credits_pic_blank.gif +0 -0
- data/guides/output/images/csrf.png +0 -0
- data/guides/output/images/customized_error_messages.png +0 -0
- data/guides/output/images/edge_badge.png +0 -0
- data/guides/output/images/error_messages.png +0 -0
- data/guides/output/images/feature_tile.gif +0 -0
- data/guides/output/images/footer_tile.gif +0 -0
- data/guides/output/images/fxn.png +0 -0
- data/guides/output/images/grey_bullet.gif +0 -0
- data/guides/output/images/habtm.png +0 -0
- data/guides/output/images/has_many.png +0 -0
- data/guides/output/images/has_many_through.png +0 -0
- data/guides/output/images/has_one.png +0 -0
- data/guides/output/images/has_one_through.png +0 -0
- data/guides/output/images/header_backdrop.png +0 -0
- data/guides/output/images/header_tile.gif +0 -0
- data/guides/output/images/i18n/demo_html_safe.png +0 -0
- data/guides/output/images/i18n/demo_localized_pirate.png +0 -0
- data/guides/output/images/i18n/demo_translated_en.png +0 -0
- data/guides/output/images/i18n/demo_translated_pirate.png +0 -0
- data/guides/output/images/i18n/demo_translation_missing.png +0 -0
- data/guides/output/images/i18n/demo_untranslated.png +0 -0
- data/guides/output/images/icons/README +5 -0
- data/guides/output/images/icons/callouts/1.png +0 -0
- data/guides/output/images/icons/callouts/10.png +0 -0
- data/guides/output/images/icons/callouts/11.png +0 -0
- data/guides/output/images/icons/callouts/12.png +0 -0
- data/guides/output/images/icons/callouts/13.png +0 -0
- data/guides/output/images/icons/callouts/14.png +0 -0
- data/guides/output/images/icons/callouts/15.png +0 -0
- data/guides/output/images/icons/callouts/2.png +0 -0
- data/guides/output/images/icons/callouts/3.png +0 -0
- data/guides/output/images/icons/callouts/4.png +0 -0
- data/guides/output/images/icons/callouts/5.png +0 -0
- data/guides/output/images/icons/callouts/6.png +0 -0
- data/guides/output/images/icons/callouts/7.png +0 -0
- data/guides/output/images/icons/callouts/8.png +0 -0
- data/guides/output/images/icons/callouts/9.png +0 -0
- data/guides/output/images/icons/caution.png +0 -0
- data/guides/output/images/icons/example.png +0 -0
- data/guides/output/images/icons/home.png +0 -0
- data/guides/output/images/icons/important.png +0 -0
- data/guides/output/images/icons/next.png +0 -0
- data/guides/output/images/icons/note.png +0 -0
- data/guides/output/images/icons/prev.png +0 -0
- data/guides/output/images/icons/tip.png +0 -0
- data/guides/output/images/icons/up.png +0 -0
- data/guides/output/images/icons/warning.png +0 -0
- data/guides/output/images/jaimeiniesta.jpg +0 -0
- data/guides/output/images/nav_arrow.gif +0 -0
- data/guides/output/images/polymorphic.png +0 -0
- data/guides/output/images/posts_index.png +0 -0
- data/guides/output/images/radar.png +0 -0
- data/guides/output/images/rails_guides_logo.gif +0 -0
- data/guides/output/images/rails_logo_remix.gif +0 -0
- data/guides/output/images/rails_welcome.png +0 -0
- data/guides/output/images/session_fixation.png +0 -0
- data/guides/output/images/tab_grey.gif +0 -0
- data/guides/output/images/tab_info.gif +0 -0
- data/guides/output/images/tab_note.gif +0 -0
- data/guides/output/images/tab_red.gif +0 -0
- data/guides/output/images/tab_yellow.gif +0 -0
- data/guides/output/images/tab_yellow.png +0 -0
- data/guides/output/images/validation_error_messages.png +0 -0
- data/guides/output/images/vijaydev.jpg +0 -0
- data/guides/output/index.html +300 -0
- data/guides/output/initialization.html +1087 -0
- data/guides/output/javascripts/guides.js +7 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushAS3.js +59 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushAppleScript.js +75 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushBash.js +59 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushCSharp.js +65 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushColdFusion.js +100 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushCpp.js +97 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushCss.js +91 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushDelphi.js +55 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushDiff.js +41 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushErlang.js +52 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushGroovy.js +67 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushJScript.js +52 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushJava.js +57 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushJavaFX.js +58 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPerl.js +72 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPhp.js +88 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPlain.js +33 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPowerShell.js +74 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPython.js +64 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushRuby.js +55 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushSass.js +94 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushScala.js +51 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushSql.js +66 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushVb.js +56 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushXml.js +69 -0
- data/guides/output/javascripts/syntaxhighlighter/shCore.js +17 -0
- data/guides/output/layout.html +312 -0
- data/guides/output/layouts_and_rendering.html +1257 -0
- data/guides/output/migrations.html +751 -0
- data/guides/output/nested_model_forms.html +350 -0
- data/guides/output/performance_testing.html +858 -0
- data/guides/output/plugins.html +590 -0
- data/guides/output/rails_application_templates.html +368 -0
- data/guides/output/rails_on_rack.html +408 -0
- data/guides/output/routing.html +1246 -0
- data/guides/output/ruby_on_rails_guides_guidelines.html +218 -0
- data/guides/output/security.html +968 -0
- data/guides/output/stylesheets/fixes.css +16 -0
- data/guides/output/stylesheets/main.css +445 -0
- data/guides/output/stylesheets/print.css +52 -0
- data/guides/output/stylesheets/reset.css +43 -0
- data/guides/output/stylesheets/style.css +13 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCore.css +226 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreDefault.css +328 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreDjango.css +331 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreEclipse.css +339 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreEmacs.css +324 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +328 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreMDUltra.css +324 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreMidnight.css +324 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreRDark.css +324 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeDefault.css +117 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeDjango.css +120 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeEclipse.css +128 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeEmacs.css +113 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +117 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeMDUltra.css +113 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeMidnight.css +113 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeRDark.css +113 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +116 -0
- data/guides/output/testing.html +1182 -0
- data/guides/source/active_record_validations_callbacks.textile +3 -3
- data/guides/source/active_support_core_extensions.textile +2 -2
- data/guides/source/asset_pipeline.textile +7 -5
- data/guides/source/association_basics.textile +2 -4
- data/guides/source/command_line.textile +1 -1
- data/guides/source/configuring.textile +4 -2
- data/guides/source/contributing_to_ruby_on_rails.textile +6 -6
- data/guides/source/initialization.textile +2 -2
- data/guides/source/performance_testing.textile +1 -1
- data/guides/source/routing.textile +1 -1
- data/guides/source/security.textile +2 -2
- data/lib/rails/commands/server.rb +1 -1
- data/lib/rails/engine.rb +1 -1
- data/lib/rails/generators/app_base.rb +2 -1
- data/lib/rails/generators/base.rb +3 -3
- data/lib/rails/generators/rails/app/templates/gitignore +15 -5
- data/lib/rails/rack.rb +0 -1
- data/lib/rails/tasks/documentation.rake +7 -7
- data/lib/rails/tasks/misc.rake +0 -2
- data/lib/rails/test_unit/testing.rake +2 -0
- data/lib/rails/version.rb +2 -2
- metadata +495 -326
- data/CHANGELOG +0 -2371
- data/lib/rails/rack/content_length.rb +0 -38
@@ -0,0 +1,252 @@
|
|
1
|
+
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
|
2
|
+
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
3
|
+
|
4
|
+
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
5
|
+
<head>
|
6
|
+
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
|
7
|
+
|
8
|
+
<title>Ruby on Rails Guides: Active Resource Basics</title>
|
9
|
+
|
10
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
|
11
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
|
12
|
+
|
13
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
|
14
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
|
15
|
+
|
16
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
|
17
|
+
</head>
|
18
|
+
<body class="guide">
|
19
|
+
<div id="topNav">
|
20
|
+
<div class="wrapper">
|
21
|
+
<strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
|
22
|
+
<a href="http://rubyonrails.org/">Overview</a> |
|
23
|
+
<a href="http://rubyonrails.org/download">Download</a> |
|
24
|
+
<a href="http://rubyonrails.org/deploy">Deploy</a> |
|
25
|
+
<a href="https://github.com/rails/rails">Code</a> |
|
26
|
+
<a href="http://rubyonrails.org/screencasts">Screencasts</a> |
|
27
|
+
<a href="http://rubyonrails.org/documentation">Documentation</a> |
|
28
|
+
<a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
|
29
|
+
<a href="http://rubyonrails.org/community">Community</a> |
|
30
|
+
<a href="http://weblog.rubyonrails.org/">Blog</a>
|
31
|
+
</div>
|
32
|
+
</div>
|
33
|
+
<div id="header">
|
34
|
+
<div class="wrapper clearfix">
|
35
|
+
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
|
36
|
+
<p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
|
37
|
+
<ul class="nav">
|
38
|
+
<li><a href="index.html">Home</a></li>
|
39
|
+
<li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">Guides Index</a>
|
40
|
+
<div id="guides" class="clearfix" style="display: none;">
|
41
|
+
<hr />
|
42
|
+
<dl class="L">
|
43
|
+
<dt>Start Here</dt>
|
44
|
+
<dd><a href="getting_started.html">Getting Started with Rails</a></dd>
|
45
|
+
<dt>Models</dt>
|
46
|
+
<dd><a href="migrations.html">Rails Database Migrations</a></dd>
|
47
|
+
<dd><a href="active_record_validations_callbacks.html">Active Record Validations and Callbacks</a></dd>
|
48
|
+
<dd><a href="association_basics.html">Active Record Associations</a></dd>
|
49
|
+
<dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
|
50
|
+
<dt>Views</dt>
|
51
|
+
<dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
|
52
|
+
<dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
|
53
|
+
<dt>Controllers</dt>
|
54
|
+
<dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
|
55
|
+
<dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
|
56
|
+
</dl>
|
57
|
+
<dl class="R">
|
58
|
+
<dt>Digging Deeper</dt>
|
59
|
+
<dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
|
60
|
+
<dd><a href="i18n.html">Rails Internationalization API</a></dd>
|
61
|
+
<dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
|
62
|
+
<dd><a href="testing.html">Testing Rails Applications</a></dd>
|
63
|
+
<dd><a href="security.html">Securing Rails Applications</a></dd>
|
64
|
+
<dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
|
65
|
+
<dd><a href="performance_testing.html">Performance Testing Rails Applications</a></dd>
|
66
|
+
<dd><a href="configuring.html">Configuring Rails Applications</a></dd>
|
67
|
+
<dd><a href="command_line.html">Rails Command Line Tools and Rake Tasks</a></dd>
|
68
|
+
<dd><a href="caching_with_rails.html">Caching with Rails</a></dd>
|
69
|
+
<dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
|
70
|
+
|
71
|
+
<dt>Extending Rails</dt>
|
72
|
+
<dd><a href="plugins.html">The Basics of Creating Rails Plugins</a></dd>
|
73
|
+
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
|
74
|
+
<dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
|
75
|
+
|
76
|
+
<dt>Contributing to Ruby on Rails</dt>
|
77
|
+
<dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
|
78
|
+
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
|
79
|
+
<dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
|
80
|
+
|
81
|
+
<dt>Release Notes</dt>
|
82
|
+
<dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</a></dd>
|
83
|
+
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
|
84
|
+
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
|
85
|
+
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
|
86
|
+
</dl>
|
87
|
+
</div>
|
88
|
+
</li>
|
89
|
+
<li><a href="contributing_to_ruby_on_rails.html">Contribute</a></li>
|
90
|
+
<li><a href="credits.html">Credits</a></li>
|
91
|
+
</ul>
|
92
|
+
</div>
|
93
|
+
</div>
|
94
|
+
<hr class="hide" />
|
95
|
+
|
96
|
+
<div id="feature">
|
97
|
+
<div class="wrapper">
|
98
|
+
<h2>Active Resource Basics</h2>
|
99
|
+
<p>This guide should provide you with all you need to get started managing the connection between business objects and RESTful web services. It implements a way to map web-based resources to local objects with <span class="caps">CRUD</span> semantics.</p>
|
100
|
+
|
101
|
+
<div id="subCol">
|
102
|
+
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
|
103
|
+
<ol class="chapters">
|
104
|
+
<li><a href="#introduction">Introduction</a></li><li><a href="#configuration-and-usage">Configuration and Usage</a></li><li><a href="#reading-and-writing-data">Reading and Writing Data</a><ul><li><a href="#read">Read</a></li> <li><a href="#create">Create</a></li> <li><a href="#update">Update</a></li> <li><a href="#delete">Delete</a></li></ul></li><li><a href="#validations">Validations</a><ul><li><a href="#validating-client-side-resources-by-overriding-validation-methods-in-base-class">Validating client side resources by overriding validation methods in base class</a></li> <li><a href="#validating-client-side-resources">Validating client side resources</a></li> <li><a href="#public-instance-methods">Public instance methods</a></li></ul></li></ol></div>
|
105
|
+
</div>
|
106
|
+
</div>
|
107
|
+
|
108
|
+
<div id="container">
|
109
|
+
<div class="wrapper">
|
110
|
+
<div id="mainCol">
|
111
|
+
<div class="warning"><p>This Guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails.</p></div>
|
112
|
+
<h3 id="introduction">1 Introduction</h3>
|
113
|
+
<p>Active Resource allows you to connect with RESTful web services. So, in Rails, Resource classes inherited from <tt>ActiveResource::Base</tt> and live in <tt>app/models</tt>.</p>
|
114
|
+
<h3 id="configuration-and-usage">2 Configuration and Usage</h3>
|
115
|
+
<p>Putting Active Resource to use is very similar to Active Record. It’s as simple as creating a model class
|
116
|
+
that inherits from ActiveResource::Base and providing a <tt>site</tt> class variable to it:</p>
|
117
|
+
<div class="code_container">
|
118
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
119
|
+
class Person < ActiveResource::Base
|
120
|
+
self.site = "http://api.people.com:3000/"
|
121
|
+
end
|
122
|
+
</pre>
|
123
|
+
</div>
|
124
|
+
<p>Now the Person class is <span class="caps">REST</span> enabled and can invoke <span class="caps">REST</span> services very similarly to how Active Record invokes
|
125
|
+
life cycle methods that operate against a persistent store.</p>
|
126
|
+
<h3 id="reading-and-writing-data">3 Reading and Writing Data</h3>
|
127
|
+
<p>Active Resource make request over <span class="caps">HTTP</span> using a standard <span class="caps">JSON</span> format. It mirrors the RESTful routing built into Action Controller but will also work with any other <span class="caps">REST</span> service that properly implements the protocol.</p>
|
128
|
+
<h4 id="read">3.1 Read</h4>
|
129
|
+
<p>Read requests use the <span class="caps">GET</span> method and expect the <span class="caps">JSON</span> form of whatever resource/resources is/are being requested.</p>
|
130
|
+
<div class="code_container">
|
131
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
132
|
+
# Find a person with id = 1
|
133
|
+
person = Person.find(1)
|
134
|
+
# Check if a person exists with id = 1
|
135
|
+
Person.exists?(1) # => true
|
136
|
+
# Get all resources of Person class
|
137
|
+
Person.all
|
138
|
+
</pre>
|
139
|
+
</div>
|
140
|
+
<h4 id="create">3.2 Create</h4>
|
141
|
+
<p>Creating a new resource submits the <span class="caps">JSON</span> form of the resource as the body of the request with <span class="caps">HTTP</span> <span class="caps">POST</span> method and parse the response into Active Resource object.</p>
|
142
|
+
<div class="code_container">
|
143
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
144
|
+
person = Person.create(:name => 'Vishnu')
|
145
|
+
person.id # => 1
|
146
|
+
</pre>
|
147
|
+
</div>
|
148
|
+
<h4 id="update">3.3 Update</h4>
|
149
|
+
<p>To update an existing resource, ‘save’ method is used. This method make a <span class="caps">HTTP</span> <span class="caps">PUT</span> request in <span class="caps">JSON</span> format.</p>
|
150
|
+
<div class="code_container">
|
151
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
152
|
+
person = Person.find(1)
|
153
|
+
person.name = 'Atrai'
|
154
|
+
person.save
|
155
|
+
</pre>
|
156
|
+
</div>
|
157
|
+
<h4 id="delete">3.4 Delete</h4>
|
158
|
+
<p>‘destroy’ method makes a <span class="caps">HTTP</span> <span class="caps">DELETE</span> request for an existing resource in <span class="caps">JSON</span> format to delete that resource.</p>
|
159
|
+
<div class="code_container">
|
160
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
161
|
+
person = Person.find(1)
|
162
|
+
person.destroy
|
163
|
+
</pre>
|
164
|
+
</div>
|
165
|
+
<h3 id="validations">4 Validations</h3>
|
166
|
+
<p>Module to support validation and errors with Active Resource objects. The module overrides Base#save to rescue ActiveResource::ResourceInvalid exceptions and parse the errors returned in the web service response. The module also adds an errors collection that mimics the interface of the errors provided by ActiveRecord::Errors.</p>
|
167
|
+
<h4 id="validating-client-side-resources-by-overriding-validation-methods-in-base-class">4.1 Validating client side resources by overriding validation methods in base class</h4>
|
168
|
+
<div class="code_container">
|
169
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
170
|
+
class Person < ActiveResource::Base
|
171
|
+
self.site = "http://api.people.com:3000/"
|
172
|
+
|
173
|
+
protected
|
174
|
+
|
175
|
+
def validate
|
176
|
+
errors.add("last", "has invalid characters") unless last =~ /[a-zA-Z]*/
|
177
|
+
end
|
178
|
+
end
|
179
|
+
</pre>
|
180
|
+
</div>
|
181
|
+
<h4 id="validating-client-side-resources">4.2 Validating client side resources</h4>
|
182
|
+
<p>Consider a Person resource on the server requiring both a first_name and a last_name with a validates_presence_of :first_name, :last_name declaration in the model:</p>
|
183
|
+
<div class="code_container">
|
184
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
185
|
+
person = Person.new(:first_name => "Jim", :last_name => "")
|
186
|
+
person.save # => false (server returns an HTTP 422 status code and errors)
|
187
|
+
person.valid? # => false
|
188
|
+
person.errors.empty? # => false
|
189
|
+
person.errors.count # => 1
|
190
|
+
person.errors.full_messages # => ["Last name can't be empty"]
|
191
|
+
person.errors[:last_name] # => ["can't be empty"]
|
192
|
+
person.last_name = "Halpert"
|
193
|
+
person.save # => true (and person is now saved to the remote service)
|
194
|
+
</pre>
|
195
|
+
</div>
|
196
|
+
<h4 id="public-instance-methods">4.3 Public instance methods</h4>
|
197
|
+
<p>ActiveResource::Validations have three public instance methods</p>
|
198
|
+
<h5 id="errors">4.3.1 errors()</h5>
|
199
|
+
<p>This will return errors object that holds all information about attribute error messages</p>
|
200
|
+
<h5 id="save_with_validation-options-nil">4.3.2 save_with_validation(options=nil)</h5>
|
201
|
+
<p>This validates the resource with any local validations written in base class and then it will try to <span class="caps">POST</span> if there are no errors.</p>
|
202
|
+
<h5 id="valid">4.3.3 valid?</h5>
|
203
|
+
<p>Runs all the local validations and will return true if no errors.</p>
|
204
|
+
|
205
|
+
<h3>Feedback</h3>
|
206
|
+
<p>
|
207
|
+
You're encouraged to help improve the quality of this guide.
|
208
|
+
</p>
|
209
|
+
<p>
|
210
|
+
If you see any typos or factual errors you are confident to
|
211
|
+
patch, please clone <a href="https://github.com/lifo/docrails">docrails</a>
|
212
|
+
and push the change yourself. That branch of Rails has public write access.
|
213
|
+
Commits are still reviewed, but that happens after you've submitted your
|
214
|
+
contribution. <a href="https://github.com/lifo/docrails">docrails</a> is
|
215
|
+
cross-merged with master periodically.
|
216
|
+
</p>
|
217
|
+
<p>
|
218
|
+
You may also find incomplete content, or stuff that is not up to date.
|
219
|
+
Please do add any missing documentation for master. Check the
|
220
|
+
<a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
|
221
|
+
for style and conventions.
|
222
|
+
</p>
|
223
|
+
<p>
|
224
|
+
If for whatever reason you spot something to fix but cannot patch it yourself, please
|
225
|
+
<a href="https://github.com/rails/rails/issues">open an issue</a>.
|
226
|
+
</p>
|
227
|
+
<p>And last but not least, any kind of discussion regarding Ruby on Rails
|
228
|
+
documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
|
229
|
+
</p>
|
230
|
+
</div>
|
231
|
+
</div>
|
232
|
+
</div>
|
233
|
+
|
234
|
+
<hr class="hide" />
|
235
|
+
<div id="footer">
|
236
|
+
<div class="wrapper">
|
237
|
+
<p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p>
|
238
|
+
<p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
|
239
|
+
</div>
|
240
|
+
</div>
|
241
|
+
|
242
|
+
<script type="text/javascript" src="javascripts/guides.js"></script>
|
243
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
|
244
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
|
245
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
|
246
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
|
247
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
|
248
|
+
<script type="text/javascript">
|
249
|
+
SyntaxHighlighter.all()
|
250
|
+
</script>
|
251
|
+
</body>
|
252
|
+
</html>
|
@@ -0,0 +1,3374 @@
|
|
1
|
+
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
|
2
|
+
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
3
|
+
|
4
|
+
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
5
|
+
<head>
|
6
|
+
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
|
7
|
+
|
8
|
+
<title>Ruby on Rails Guides: Active Support Core Extensions</title>
|
9
|
+
|
10
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
|
11
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
|
12
|
+
|
13
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
|
14
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
|
15
|
+
|
16
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
|
17
|
+
</head>
|
18
|
+
<body class="guide">
|
19
|
+
<div id="topNav">
|
20
|
+
<div class="wrapper">
|
21
|
+
<strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
|
22
|
+
<a href="http://rubyonrails.org/">Overview</a> |
|
23
|
+
<a href="http://rubyonrails.org/download">Download</a> |
|
24
|
+
<a href="http://rubyonrails.org/deploy">Deploy</a> |
|
25
|
+
<a href="https://github.com/rails/rails">Code</a> |
|
26
|
+
<a href="http://rubyonrails.org/screencasts">Screencasts</a> |
|
27
|
+
<a href="http://rubyonrails.org/documentation">Documentation</a> |
|
28
|
+
<a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
|
29
|
+
<a href="http://rubyonrails.org/community">Community</a> |
|
30
|
+
<a href="http://weblog.rubyonrails.org/">Blog</a>
|
31
|
+
</div>
|
32
|
+
</div>
|
33
|
+
<div id="header">
|
34
|
+
<div class="wrapper clearfix">
|
35
|
+
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
|
36
|
+
<p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
|
37
|
+
<ul class="nav">
|
38
|
+
<li><a href="index.html">Home</a></li>
|
39
|
+
<li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">Guides Index</a>
|
40
|
+
<div id="guides" class="clearfix" style="display: none;">
|
41
|
+
<hr />
|
42
|
+
<dl class="L">
|
43
|
+
<dt>Start Here</dt>
|
44
|
+
<dd><a href="getting_started.html">Getting Started with Rails</a></dd>
|
45
|
+
<dt>Models</dt>
|
46
|
+
<dd><a href="migrations.html">Rails Database Migrations</a></dd>
|
47
|
+
<dd><a href="active_record_validations_callbacks.html">Active Record Validations and Callbacks</a></dd>
|
48
|
+
<dd><a href="association_basics.html">Active Record Associations</a></dd>
|
49
|
+
<dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
|
50
|
+
<dt>Views</dt>
|
51
|
+
<dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
|
52
|
+
<dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
|
53
|
+
<dt>Controllers</dt>
|
54
|
+
<dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
|
55
|
+
<dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
|
56
|
+
</dl>
|
57
|
+
<dl class="R">
|
58
|
+
<dt>Digging Deeper</dt>
|
59
|
+
<dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
|
60
|
+
<dd><a href="i18n.html">Rails Internationalization API</a></dd>
|
61
|
+
<dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
|
62
|
+
<dd><a href="testing.html">Testing Rails Applications</a></dd>
|
63
|
+
<dd><a href="security.html">Securing Rails Applications</a></dd>
|
64
|
+
<dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
|
65
|
+
<dd><a href="performance_testing.html">Performance Testing Rails Applications</a></dd>
|
66
|
+
<dd><a href="configuring.html">Configuring Rails Applications</a></dd>
|
67
|
+
<dd><a href="command_line.html">Rails Command Line Tools and Rake Tasks</a></dd>
|
68
|
+
<dd><a href="caching_with_rails.html">Caching with Rails</a></dd>
|
69
|
+
<dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
|
70
|
+
|
71
|
+
<dt>Extending Rails</dt>
|
72
|
+
<dd><a href="plugins.html">The Basics of Creating Rails Plugins</a></dd>
|
73
|
+
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
|
74
|
+
<dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
|
75
|
+
|
76
|
+
<dt>Contributing to Ruby on Rails</dt>
|
77
|
+
<dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
|
78
|
+
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
|
79
|
+
<dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
|
80
|
+
|
81
|
+
<dt>Release Notes</dt>
|
82
|
+
<dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</a></dd>
|
83
|
+
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
|
84
|
+
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
|
85
|
+
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
|
86
|
+
</dl>
|
87
|
+
</div>
|
88
|
+
</li>
|
89
|
+
<li><a href="contributing_to_ruby_on_rails.html">Contribute</a></li>
|
90
|
+
<li><a href="credits.html">Credits</a></li>
|
91
|
+
</ul>
|
92
|
+
</div>
|
93
|
+
</div>
|
94
|
+
<hr class="hide" />
|
95
|
+
|
96
|
+
<div id="feature">
|
97
|
+
<div class="wrapper">
|
98
|
+
<h2>Active Support Core Extensions</h2>
|
99
|
+
<p>Active Support is the Ruby on Rails component responsible for providing Ruby language extensions, utilities, and other transversal stuff.</p>
|
100
|
+
<p>It offers a richer bottom-line at the language level, targeted both at the development of Rails applications, and at the development of Ruby on Rails itself.</p>
|
101
|
+
<p>By referring to this guide you will learn the extensions to the Ruby core classes and modules provided by Active Support.</p>
|
102
|
+
|
103
|
+
<div id="subCol">
|
104
|
+
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
|
105
|
+
<ol class="chapters">
|
106
|
+
<li><a href="#how-to-load-core-extensions">How to Load Core Extensions</a><ul><li><a href="#stand-alone-active-support">Stand-Alone Active Support</a></li> <li><a href="#active-support-within-a-ruby-on-rails-application">Active Support Within a Ruby on Rails Application</a></li></ul></li><li><a href="#extensions-to-all-objects">Extensions to All Objects</a><ul><li><a href="#blank-and-present"><tt>blank?</tt> and <tt>present?</tt></a></li> <li><a href="#presence"><tt>presence</tt></a></li> <li><a href="#duplicable"><tt>duplicable?</tt></a></li> <li><a href="#try"><tt>try</tt></a></li> <li><a href="#singleton_class"><tt>singleton_class</tt></a></li> <li><a href="#class_eval-args-block"><tt>class_eval(*args, &block)</tt></a></li> <li><a href="#acts_like-duck"><tt>acts_like?(duck)</tt></a></li> <li><a href="#to_param"><tt>to_param</tt></a></li> <li><a href="#to_query"><tt>to_query</tt></a></li> <li><a href="#with_options"><tt>with_options</tt></a></li> <li><a href="#instance-variables">Instance Variables</a></li> <li><a href="#silencing-warnings-streams-and-exceptions">Silencing Warnings, Streams, and Exceptions</a></li> <li><a href="#in"><tt>in?</tt></a></li></ul></li><li><a href="#extensions-to-module">Extensions to <tt>Module</tt></a><ul><li><a href="#alias_method_chain"><tt>alias_method_chain</tt></a></li> <li><a href="#attributes">Attributes</a></li> <li><a href="#parents">Parents</a></li> <li><a href="#constants">Constants</a></li> <li><a href="#synchronization">Synchronization</a></li> <li><a href="#reachable">Reachable</a></li> <li><a href="#anonymous">Anonymous</a></li> <li><a href="#method-delegation">Method Delegation</a></li> <li><a href="#method-names">Method Names</a></li> <li><a href="#redefining-methods">Redefining Methods</a></li></ul></li><li><a href="#extensions-to-class">Extensions to <tt>Class</tt></a><ul><li><a href="#class-attributes">Class Attributes</a></li> <li><a href="#class-inheritable-attributes">Class Inheritable Attributes</a></li> <li><a href="#subclasses-descendants">Subclasses & Descendants</a></li></ul></li><li><a href="#extensions-to-string">Extensions to <tt>String</tt></a><ul><li><a href="#output-safety">Output Safety</a></li> <li><a href="#squish"><tt>squish</tt></a></li> <li><a href="#truncate"><tt>truncate</tt></a></li> <li><a href="#inquiry"><tt>inquiry</tt></a></li> <li><a href="#key-based-interpolation">Key-based Interpolation</a></li> <li><a href="#starts_with-and-ends_with"><tt>starts_with?</tt> and <tt>ends_with?</tt></a></li> <li><a href="#strip_heredoc"><tt>strip_heredoc</tt></a></li> <li><a href="#access">Access</a></li> <li><a href="#inflections">Inflections</a></li> <li><a href="#string-conversions">Conversions</a></li></ul></li><li><a href="#extensions-to-numeric">Extensions to <tt>Numeric</tt></a><ul><li><a href="#bytes">Bytes</a></li></ul></li><li><a href="#extensions-to-integer">Extensions to <tt>Integer</tt></a><ul><li><a href="#multiple_of"><tt>multiple_of?</tt></a></li> <li><a href="#ordinalize"><tt>ordinalize</tt></a></li></ul></li><li><a href="#extensions-to-float">Extensions to <tt>Float</tt></a><ul><li><a href="#round"><tt>round</tt></a></li></ul></li><li><a href="#extensions-to-bigdecimal">Extensions to <tt>BigDecimal</tt></a></li><li><a href="#extensions-to-enumerable">Extensions to <tt>Enumerable</tt></a><ul><li><a href="#group_by"><tt>group_by</tt></a></li> <li><a href="#sum"><tt>sum</tt></a></li> <li><a href="#each_with_object"><tt>each_with_object</tt></a></li> <li><a href="#index_by"><tt>index_by</tt></a></li> <li><a href="#many"><tt>many?</tt></a></li> <li><a href="#exclude"><tt>exclude?</tt></a></li></ul></li><li><a href="#extensions-to-array">Extensions to <tt>Array</tt></a><ul><li><a href="#accessing">Accessing</a></li> <li><a href="#random-access">Random Access</a></li> <li><a href="#adding-elements">Adding Elements</a></li> <li><a href="#options-extraction">Options Extraction</a></li> <li><a href="#array-conversions">Conversions</a></li> <li><a href="#wrapping">Wrapping</a></li> <li><a href="#grouping">Grouping</a></li></ul></li><li><a href="#extensions-to-hash">Extensions to <tt>Hash</tt></a><ul><li><a href="#hash-conversions">Conversions</a></li> <li><a href="#merging">Merging</a></li> <li><a href="#diffing">Diffing</a></li> <li><a href="#working-with-keys">Working with Keys</a></li> <li><a href="#slicing">Slicing</a></li> <li><a href="#extracting">Extracting</a></li> <li><a href="#indifferent-access">Indifferent Access</a></li></ul></li><li><a href="#extensions-to-regexp">Extensions to <tt>Regexp</tt></a><ul><li><a href="#multiline"><tt>multiline?</tt></a></li></ul></li><li><a href="#extensions-to-range">Extensions to <tt>Range</tt></a><ul><li><a href="#to_s"><tt>to_s</tt></a></li> <li><a href="#step"><tt>step</tt></a></li> <li><a href="#include"><tt>include?</tt></a></li> <li><a href="#cover"><tt>cover?</tt></a></li> <li><a href="#overlaps"><tt>overlaps?</tt></a></li></ul></li><li><a href="#extensions-to-proc">Extensions to <tt>Proc</tt></a><ul><li><a href="#bind"><tt>bind</tt></a></li></ul></li><li><a href="#extensions-to-date">Extensions to <tt>Date</tt></a><ul><li><a href="#calculations">Calculations</a></li> <li><a href="#date-conversions">Conversions</a></li></ul></li><li><a href="#extensions-to-datetime">Extensions to <tt>DateTime</tt></a><ul><li><a href="#calculations-datetime">Calculations</a></li></ul></li><li><a href="#extensions-to-time">Extensions to <tt>Time</tt></a><ul><li><a href="#time-calculations">Calculations</a></li> <li><a href="#time-constructors">Time Constructors</a></li></ul></li><li><a href="#extensions-to-process">Extensions to <tt>Process</tt></a><ul><li><a href="#daemon"><tt>daemon</tt></a></li></ul></li><li><a href="#extensions-to-file">Extensions to <tt>File</tt></a><ul><li><a href="#atomic_write"><tt>atomic_write</tt></a></li></ul></li><li><a href="#extensions-to-logger">Extensions to <tt>Logger</tt></a><ul><li><a href="#around_-level"><tt>around_[level]</tt></a></li> <li><a href="#silence"><tt>silence</tt></a></li> <li><a href="#datetime_format"><tt>datetime_format=</tt></a></li></ul></li><li><a href="#extensions-to-nameerror">Extensions to <tt>NameError</tt></a></li><li><a href="#extensions-to-loaderror">Extensions to <tt>LoadError</tt></a></li></ol></div>
|
107
|
+
</div>
|
108
|
+
</div>
|
109
|
+
|
110
|
+
<div id="container">
|
111
|
+
<div class="wrapper">
|
112
|
+
<div id="mainCol">
|
113
|
+
<h3 id="how-to-load-core-extensions">1 How to Load Core Extensions</h3>
|
114
|
+
<h4 id="stand-alone-active-support">1.1 Stand-Alone Active Support</h4>
|
115
|
+
<p>In order to have a near zero default footprint, Active Support does not load anything by default. It is broken in small pieces so that you may load just what you need, and also has some convenience entry points to load related extensions in one shot, even everything.</p>
|
116
|
+
<p>Thus, after a simple require like:</p>
|
117
|
+
<div class="code_container">
|
118
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
119
|
+
require 'active_support'
|
120
|
+
</pre>
|
121
|
+
</div>
|
122
|
+
<p>objects do not even respond to <tt>blank?</tt>. Let’s see how to load its definition.</p>
|
123
|
+
<h5 id="cherry-picking-a-definition">1.1.1 Cherry-picking a Definition</h5>
|
124
|
+
<p>The most lightweight way to get <tt>blank?</tt> is to cherry-pick the file that defines it.</p>
|
125
|
+
<p>For every single method defined as a core extension this guide has a note that says where such a method is defined. In the case of <tt>blank?</tt> the note reads:</p>
|
126
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/object/blank.rb</tt>.</p></div>
|
127
|
+
<p>That means that this single call is enough:</p>
|
128
|
+
<div class="code_container">
|
129
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
130
|
+
require 'active_support/core_ext/object/blank'
|
131
|
+
</pre>
|
132
|
+
</div>
|
133
|
+
<p>Active Support has been carefully revised so that cherry-picking a file loads only strictly needed dependencies, if any.</p>
|
134
|
+
<h5 id="loading-grouped-core-extensions">1.1.2 Loading Grouped Core Extensions</h5>
|
135
|
+
<p>The next level is to simply load all extensions to <tt>Object</tt>. As a rule of thumb, extensions to <tt>SomeClass</tt> are available in one shot by loading <tt>active_support/core_ext/some_class</tt>.</p>
|
136
|
+
<p>Thus, to load all extensions to <tt>Object</tt> (including <tt>blank?</tt>):</p>
|
137
|
+
<div class="code_container">
|
138
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
139
|
+
require 'active_support/core_ext/object'
|
140
|
+
</pre>
|
141
|
+
</div>
|
142
|
+
<h5 id="loading-all-core-extensions">1.1.3 Loading All Core Extensions</h5>
|
143
|
+
<p>You may prefer just to load all core extensions, there is a file for that:</p>
|
144
|
+
<div class="code_container">
|
145
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
146
|
+
require 'active_support/core_ext'
|
147
|
+
</pre>
|
148
|
+
</div>
|
149
|
+
<h5 id="loading-all-active-support">1.1.4 Loading All Active Support</h5>
|
150
|
+
<p>And finally, if you want to have all Active Support available just issue:</p>
|
151
|
+
<div class="code_container">
|
152
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
153
|
+
require 'active_support/all'
|
154
|
+
</pre>
|
155
|
+
</div>
|
156
|
+
<p>That does not even put the entire Active Support in memory upfront indeed, some stuff is configured via <tt>autoload</tt>, so it is only loaded if used.</p>
|
157
|
+
<h4 id="active-support-within-a-ruby-on-rails-application">1.2 Active Support Within a Ruby on Rails Application</h4>
|
158
|
+
<p>A Ruby on Rails application loads all Active Support unless <tt>config.active_support.bare</tt> is true. In that case, the application will only load what the framework itself cherry-picks for its own needs, and can still cherry-pick itself at any granularity level, as explained in the previous section.</p>
|
159
|
+
<h3 id="extensions-to-all-objects">2 Extensions to All Objects</h3>
|
160
|
+
<h4 id="blank-and-present">2.1 <tt>blank?</tt> and <tt>present?</tt></h4>
|
161
|
+
<p>The following values are considered to be blank in a Rails application:</p>
|
162
|
+
<ul>
|
163
|
+
<li><tt>nil</tt> and <tt>false</tt>,</li>
|
164
|
+
</ul>
|
165
|
+
<ul>
|
166
|
+
<li>strings composed only of whitespace (see note below),</li>
|
167
|
+
</ul>
|
168
|
+
<ul>
|
169
|
+
<li>empty arrays and hashes, and</li>
|
170
|
+
</ul>
|
171
|
+
<ul>
|
172
|
+
<li>any other object that responds to <tt>empty?</tt> and it is empty.</li>
|
173
|
+
</ul>
|
174
|
+
<div class="info"><p>In Ruby 1.9 the predicate for strings uses the Unicode-aware character class <tt>[:space:]</tt>, so for example U<tt>2029 (paragraph separator) is considered to be whitespace. In Ruby 1.8 whitespace is considered to be <tt>\s</tt> together with the ideographic space U</tt>3000.</p></div>
|
175
|
+
<div class="warning"><p>Note that numbers are not mentioned, in particular 0 and 0.0 are <strong>not</strong> blank.</p></div>
|
176
|
+
<p>For example, this method from <tt>ActionDispatch::Session::AbstractStore</tt> uses <tt>blank?</tt> for checking whether a session key is present:</p>
|
177
|
+
<div class="code_container">
|
178
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
179
|
+
def ensure_session_key!
|
180
|
+
if @key.blank?
|
181
|
+
raise ArgumentError, 'A key is required...'
|
182
|
+
end
|
183
|
+
end
|
184
|
+
</pre>
|
185
|
+
</div>
|
186
|
+
<p>The method <tt>present?</tt> is equivalent to <tt>!blank?</tt>. This example is taken from <tt>ActionDispatch::Http::Cache::Response</tt>:</p>
|
187
|
+
<div class="code_container">
|
188
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
189
|
+
def set_conditional_cache_control!
|
190
|
+
return if self["Cache-Control"].present?
|
191
|
+
...
|
192
|
+
end
|
193
|
+
</pre>
|
194
|
+
</div>
|
195
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/object/blank.rb</tt>.</p></div>
|
196
|
+
<h4 id="presence">2.2 <tt>presence</tt></h4>
|
197
|
+
<p>The <tt>presence</tt> method returns its receiver if <tt>present?</tt>, and <tt>nil</tt> otherwise. It is useful for idioms like this:</p>
|
198
|
+
<div class="code_container">
|
199
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
200
|
+
host = config[:host].presence || 'localhost'
|
201
|
+
</pre>
|
202
|
+
</div>
|
203
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/object/blank.rb</tt>.</p></div>
|
204
|
+
<h4 id="duplicable">2.3 <tt>duplicable?</tt></h4>
|
205
|
+
<p>A few fundamental objects in Ruby are singletons. For example, in the whole life of a program the integer 1 refers always to the same instance:</p>
|
206
|
+
<div class="code_container">
|
207
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
208
|
+
1.object_id # => 3
|
209
|
+
Math.cos(0).to_i.object_id # => 3
|
210
|
+
</pre>
|
211
|
+
</div>
|
212
|
+
<p>Hence, there’s no way these objects can be duplicated through <tt>dup</tt> or <tt>clone</tt>:</p>
|
213
|
+
<div class="code_container">
|
214
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
215
|
+
true.dup # => TypeError: can't dup TrueClass
|
216
|
+
</pre>
|
217
|
+
</div>
|
218
|
+
<p>Some numbers which are not singletons are not duplicable either:</p>
|
219
|
+
<div class="code_container">
|
220
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
221
|
+
0.0.clone # => allocator undefined for Float
|
222
|
+
(2**1024).clone # => allocator undefined for Bignum
|
223
|
+
</pre>
|
224
|
+
</div>
|
225
|
+
<p>Active Support provides <tt>duplicable?</tt> to programmatically query an object about this property:</p>
|
226
|
+
<div class="code_container">
|
227
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
228
|
+
"".duplicable? # => true
|
229
|
+
false.duplicable? # => false
|
230
|
+
</pre>
|
231
|
+
</div>
|
232
|
+
<p>By definition all objects are <tt>duplicable?</tt> except <tt>nil</tt>, <tt>false</tt>, <tt>true</tt>, symbols, numbers, and class and module objects.</p>
|
233
|
+
<div class="warning"><p>Any class can disallow duplication removing <tt>dup</tt> and <tt>clone</tt> or raising exceptions from them, only <tt>rescue</tt> can tell whether a given arbitrary object is duplicable. <tt>duplicable?</tt> depends on the hard-coded list above, but it is much faster than <tt>rescue</tt>. Use it only if you know the hard-coded list is enough in your use case.</p></div>
|
234
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/object/duplicable.rb</tt>.</p></div>
|
235
|
+
<h4 id="try">2.4 <tt>try</tt></h4>
|
236
|
+
<p>Sometimes you want to call a method provided the receiver object is not <tt>nil</tt>, which is something you usually check first. <tt>try</tt> is like <tt>Object#send</tt> except that it returns <tt>nil</tt> if sent to <tt>nil</tt>.</p>
|
237
|
+
<p>For instance, in this code from <tt>ActiveRecord::ConnectionAdapters::AbstractAdapter</tt> <tt>@logger</tt> could be <tt>nil</tt>, but you save the check and write in an optimistic style:</p>
|
238
|
+
<div class="code_container">
|
239
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
240
|
+
def log_info(sql, name, ms)
|
241
|
+
if @logger.try(:debug?)
|
242
|
+
name = '%s (%.1fms)' % [name || 'SQL', ms]
|
243
|
+
@logger.debug(format_log_entry(name, sql.squeeze(' ')))
|
244
|
+
end
|
245
|
+
end
|
246
|
+
</pre>
|
247
|
+
</div>
|
248
|
+
<p><tt>try</tt> can also be called without arguments but a block, which will only be executed if the object is not nil:</p>
|
249
|
+
<div class="code_container">
|
250
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
251
|
+
@person.try { |p| "#{p.first_name} #{p.last_name}" }
|
252
|
+
</pre>
|
253
|
+
</div>
|
254
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/object/try.rb</tt>.</p></div>
|
255
|
+
<h4 id="singleton_class">2.5 <tt>singleton_class</tt></h4>
|
256
|
+
<p>The method <tt>singleton_class</tt> returns the singleton class of the receiver:</p>
|
257
|
+
<div class="code_container">
|
258
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
259
|
+
String.singleton_class # => #<Class:String>
|
260
|
+
String.new.singleton_class # => #<Class:#<String:0x17a1d1c>>
|
261
|
+
</pre>
|
262
|
+
</div>
|
263
|
+
<div class="warning"><p>Fixnums and symbols have no singleton classes, <tt>singleton_class</tt> raises <tt>TypeError</tt> on them. Moreover, the singleton classes of <tt>nil</tt>, <tt>true</tt>, and <tt>false</tt>, are <tt>NilClass</tt>, <tt>TrueClass</tt>, and <tt>FalseClass</tt>, respectively.</p></div>
|
264
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/kernel/singleton_class.rb</tt>.</p></div>
|
265
|
+
<h4 id="class_eval-args-block">2.6 <tt>class_eval(*args, &block)</tt></h4>
|
266
|
+
<p>You can evaluate code in the context of any object’s singleton class using <tt>class_eval</tt>:</p>
|
267
|
+
<div class="code_container">
|
268
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
269
|
+
class Proc
|
270
|
+
def bind(object)
|
271
|
+
block, time = self, Time.now
|
272
|
+
object.class_eval do
|
273
|
+
method_name = "__bind_#{time.to_i}_#{time.usec}"
|
274
|
+
define_method(method_name, &block)
|
275
|
+
method = instance_method(method_name)
|
276
|
+
remove_method(method_name)
|
277
|
+
method
|
278
|
+
end.bind(object)
|
279
|
+
end
|
280
|
+
end
|
281
|
+
</pre>
|
282
|
+
</div>
|
283
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/kernel/singleton_class.rb</tt>.</p></div>
|
284
|
+
<h4 id="acts_like-duck">2.7 <tt>acts_like?(duck)</tt></h4>
|
285
|
+
<p>The method <tt>acts_like</tt> provides a way to check whether some class acts like some other class based on a simple convention: a class that provides the same interface as <tt>String</tt> defines</p>
|
286
|
+
<div class="code_container">
|
287
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
288
|
+
def acts_like_string?
|
289
|
+
end
|
290
|
+
</pre>
|
291
|
+
</div>
|
292
|
+
<p>which is only a marker, its body or return value are irrelevant. Then, client code can query for duck-type-safeness this way:</p>
|
293
|
+
<div class="code_container">
|
294
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
295
|
+
some_klass.acts_like?(:string)
|
296
|
+
</pre>
|
297
|
+
</div>
|
298
|
+
<p>Rails has classes that act like <tt>Date</tt> or <tt>Time</tt> and follow this contract.</p>
|
299
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/object/acts_like.rb</tt>.</p></div>
|
300
|
+
<h4 id="to_param">2.8 <tt>to_param</tt></h4>
|
301
|
+
<p>All objects in Rails respond to the method <tt>to_param</tt>, which is meant to return something that represents them as values in a query string, or as <span class="caps">URL</span> fragments.</p>
|
302
|
+
<p>By default <tt>to_param</tt> just calls <tt>to_s</tt>:</p>
|
303
|
+
<div class="code_container">
|
304
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
305
|
+
7.to_param # => "7"
|
306
|
+
</pre>
|
307
|
+
</div>
|
308
|
+
<p>The return value of <tt>to_param</tt> should <strong>not</strong> be escaped:</p>
|
309
|
+
<div class="code_container">
|
310
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
311
|
+
"Tom & Jerry".to_param # => "Tom & Jerry"
|
312
|
+
</pre>
|
313
|
+
</div>
|
314
|
+
<p>Several classes in Rails overwrite this method.</p>
|
315
|
+
<p>For example <tt>nil</tt>, <tt>true</tt>, and <tt>false</tt> return themselves. <tt>Array#to_param</tt> calls <tt>to_param</tt> on the elements and joins the result with “/”:</p>
|
316
|
+
<div class="code_container">
|
317
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
318
|
+
[0, true, String].to_param # => "0/true/String"
|
319
|
+
</pre>
|
320
|
+
</div>
|
321
|
+
<p>Notably, the Rails routing system calls <tt>to_param</tt> on models to get a value for the <tt>:id</tt> placeholder. <tt>ActiveRecord::Base#to_param</tt> returns the <tt>id</tt> of a model, but you can redefine that method in your models. For example, given</p>
|
322
|
+
<div class="code_container">
|
323
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
324
|
+
class User
|
325
|
+
def to_param
|
326
|
+
"#{id}-#{name.parameterize}"
|
327
|
+
end
|
328
|
+
end
|
329
|
+
</pre>
|
330
|
+
</div>
|
331
|
+
<p>we get:</p>
|
332
|
+
<div class="code_container">
|
333
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
334
|
+
user_path(@user) # => "/users/357-john-smith"
|
335
|
+
</pre>
|
336
|
+
</div>
|
337
|
+
<div class="warning"><p>Controllers need to be aware of any redefinition of <tt>to_param</tt> because when a request like that comes in “357-john-smith” is the value of <tt>params[:id]</tt>.</p></div>
|
338
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/object/to_param.rb</tt>.</p></div>
|
339
|
+
<h4 id="to_query">2.9 <tt>to_query</tt></h4>
|
340
|
+
<p>Except for hashes, given an unescaped <tt>key</tt> this method constructs the part of a query string that would map such key to what <tt>to_param</tt> returns. For example, given</p>
|
341
|
+
<div class="code_container">
|
342
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
343
|
+
class User
|
344
|
+
def to_param
|
345
|
+
"#{id}-#{name.parameterize}"
|
346
|
+
end
|
347
|
+
end
|
348
|
+
</pre>
|
349
|
+
</div>
|
350
|
+
<p>we get:</p>
|
351
|
+
<div class="code_container">
|
352
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
353
|
+
current_user.to_query('user') # => user=357-john-smith
|
354
|
+
</pre>
|
355
|
+
</div>
|
356
|
+
<p>This method escapes whatever is needed, both for the key and the value:</p>
|
357
|
+
<div class="code_container">
|
358
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
359
|
+
account.to_query('company[name]')
|
360
|
+
# => "company%5Bname%5D=Johnson+%26+Johnson"
|
361
|
+
</pre>
|
362
|
+
</div>
|
363
|
+
<p>so its output is ready to be used in a query string.</p>
|
364
|
+
<p>Arrays return the result of applying <tt>to_query</tt> to each element with <tt><em>key</em>[]</tt> as key, and join the result with “&”:</p>
|
365
|
+
<div class="code_container">
|
366
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
367
|
+
[3.4, -45.6].to_query('sample')
|
368
|
+
# => "sample%5B%5D=3.4&sample%5B%5D=-45.6"
|
369
|
+
</pre>
|
370
|
+
</div>
|
371
|
+
<p>Hashes also respond to <tt>to_query</tt> but with a different signature. If no argument is passed a call generates a sorted series of key/value assignments calling <tt>to_query(key)</tt> on its values. Then it joins the result with “&”:</p>
|
372
|
+
<div class="code_container">
|
373
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
374
|
+
{:c => 3, :b => 2, :a => 1}.to_query # => "a=1&b=2&c=3"
|
375
|
+
</pre>
|
376
|
+
</div>
|
377
|
+
<p>The method <tt>Hash#to_query</tt> accepts an optional namespace for the keys:</p>
|
378
|
+
<div class="code_container">
|
379
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
380
|
+
{:id => 89, :name => "John Smith"}.to_query('user')
|
381
|
+
# => "user%5Bid%5D=89&user%5Bname%5D=John+Smith"
|
382
|
+
</pre>
|
383
|
+
</div>
|
384
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/object/to_query.rb</tt>.</p></div>
|
385
|
+
<h4 id="with_options">2.10 <tt>with_options</tt></h4>
|
386
|
+
<p>The method <tt>with_options</tt> provides a way to factor out common options in a series of method calls.</p>
|
387
|
+
<p>Given a default options hash, <tt>with_options</tt> yields a proxy object to a block. Within the block, methods called on the proxy are forwarded to the receiver with their options merged. For example, you get rid of the duplication in:</p>
|
388
|
+
<div class="code_container">
|
389
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
390
|
+
class Account < ActiveRecord::Base
|
391
|
+
has_many :customers, :dependent => :destroy
|
392
|
+
has_many :products, :dependent => :destroy
|
393
|
+
has_many :invoices, :dependent => :destroy
|
394
|
+
has_many :expenses, :dependent => :destroy
|
395
|
+
end
|
396
|
+
</pre>
|
397
|
+
</div>
|
398
|
+
<p>this way:</p>
|
399
|
+
<div class="code_container">
|
400
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
401
|
+
class Account < ActiveRecord::Base
|
402
|
+
with_options :dependent => :destroy do |assoc|
|
403
|
+
assoc.has_many :customers
|
404
|
+
assoc.has_many :products
|
405
|
+
assoc.has_many :invoices
|
406
|
+
assoc.has_many :expenses
|
407
|
+
end
|
408
|
+
end
|
409
|
+
</pre>
|
410
|
+
</div>
|
411
|
+
<p>That idiom may convey <em>grouping</em> to the reader as well. For example, say you want to send a newsletter whose language depends on the user. Somewhere in the mailer you could group locale-dependent bits like this:</p>
|
412
|
+
<div class="code_container">
|
413
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
414
|
+
I18n.with_options :locale => user.locale, :scope => "newsletter" do |i18n|
|
415
|
+
subject i18n.t :subject
|
416
|
+
body i18n.t :body, :user_name => user.name
|
417
|
+
end
|
418
|
+
</pre>
|
419
|
+
</div>
|
420
|
+
<div class="info"><p>Since <tt>with_options</tt> forwards calls to its receiver they can be nested. Each nesting level will merge inherited defaults in addition to their own.</p></div>
|
421
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/object/with_options.rb</tt>.</p></div>
|
422
|
+
<h4 id="instance-variables">2.11 Instance Variables</h4>
|
423
|
+
<p>Active Support provides several methods to ease access to instance variables.</p>
|
424
|
+
<h5 id="instance_variable_names">2.11.1 <tt>instance_variable_names</tt></h5>
|
425
|
+
<p>Ruby 1.8 and 1.9 have a method called <tt>instance_variables</tt> that returns the names of the defined instance variables. But they behave differently, in 1.8 it returns strings whereas in 1.9 it returns symbols. Active Support defines <tt>instance_variable_names</tt> as a portable way to obtain them as strings:</p>
|
426
|
+
<div class="code_container">
|
427
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
428
|
+
class C
|
429
|
+
def initialize(x, y)
|
430
|
+
@x, @y = x, y
|
431
|
+
end
|
432
|
+
end
|
433
|
+
|
434
|
+
C.new(0, 1).instance_variable_names # => ["@y", "@x"]
|
435
|
+
</pre>
|
436
|
+
</div>
|
437
|
+
<div class="warning"><p>The order in which the names are returned is unspecified, and it indeed depends on the version of the interpreter.</p></div>
|
438
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/object/instance_variables.rb</tt>.</p></div>
|
439
|
+
<h5 id="instance_values">2.11.2 <tt>instance_values</tt></h5>
|
440
|
+
<p>The method <tt>instance_values</tt> returns a hash that maps instance variable names without “@” to their
|
441
|
+
corresponding values. Keys are strings both in Ruby 1.8 and 1.9:</p>
|
442
|
+
<div class="code_container">
|
443
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
444
|
+
class C
|
445
|
+
def initialize(x, y)
|
446
|
+
@x, @y = x, y
|
447
|
+
end
|
448
|
+
end
|
449
|
+
|
450
|
+
C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
|
451
|
+
</pre>
|
452
|
+
</div>
|
453
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/object/instance_variables.rb</tt>.</p></div>
|
454
|
+
<h4 id="silencing-warnings-streams-and-exceptions">2.12 Silencing Warnings, Streams, and Exceptions</h4>
|
455
|
+
<p>The methods <tt>silence_warnings</tt> and <tt>enable_warnings</tt> change the value of <tt>$VERBOSE</tt> accordingly for the duration of their block, and reset it afterwards:</p>
|
456
|
+
<div class="code_container">
|
457
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
458
|
+
silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }
|
459
|
+
</pre>
|
460
|
+
</div>
|
461
|
+
<p>You can silence any stream while a block runs with <tt>silence_stream</tt>:</p>
|
462
|
+
<div class="code_container">
|
463
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
464
|
+
silence_stream(STDOUT) do
|
465
|
+
# STDOUT is silent here
|
466
|
+
end
|
467
|
+
</pre>
|
468
|
+
</div>
|
469
|
+
<p>The <tt>quietly</tt> method addresses the common use case where you want to silence <span class="caps">STDOUT</span> and <span class="caps">STDERR</span>, even in subprocesses:</p>
|
470
|
+
<div class="code_container">
|
471
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
472
|
+
quietly { system 'bundle install' }
|
473
|
+
</pre>
|
474
|
+
</div>
|
475
|
+
<p>For example, the railties test suite uses that one in a few places to prevent command messages from being echoed intermixed with the progress status.</p>
|
476
|
+
<p>Silencing exceptions is also possible with <tt>suppress</tt>. This method receives an arbitrary number of exception classes. If an exception is raised during the execution of the block and is <tt>kind_of?</tt> any of the arguments, <tt>suppress</tt> captures it and returns silently. Otherwise the exception is reraised:</p>
|
477
|
+
<div class="code_container">
|
478
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
479
|
+
# If the user is locked the increment is lost, no big deal.
|
480
|
+
suppress(ActiveRecord::StaleObjectError) do
|
481
|
+
current_user.increment! :visits
|
482
|
+
end
|
483
|
+
</pre>
|
484
|
+
</div>
|
485
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/kernel/reporting.rb</tt>.</p></div>
|
486
|
+
<h4 id="in">2.13 <tt>in?</tt></h4>
|
487
|
+
<p>The predicate <tt>in?</tt> tests if an object is included in another object. An <tt>ArgumentError</tt> exception will be raised if the argument passed does not respond to <tt>include?</tt>.</p>
|
488
|
+
<p>Examples of <tt>in?</tt>:</p>
|
489
|
+
<div class="code_container">
|
490
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
491
|
+
1.in?([1,2]) # => true
|
492
|
+
"lo".in?("hello") # => true
|
493
|
+
25.in?(30..50) # => false
|
494
|
+
</pre>
|
495
|
+
</div>
|
496
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/object/inclusion.rb</tt>.</p></div>
|
497
|
+
<h3 id="extensions-to-module">3 Extensions to <tt>Module</tt></h3>
|
498
|
+
<h4 id="alias_method_chain">3.1 <tt>alias_method_chain</tt></h4>
|
499
|
+
<p>Using plain Ruby you can wrap methods with other methods, that’s called <em>alias chaining</em>.</p>
|
500
|
+
<p>For example, let’s say you’d like params to be strings in functional tests, as they are in real requests, but still want the convenience of assigning integers and other kind of values. To accomplish that you could wrap <tt>ActionController::TestCase#process</tt> this way in <tt>test/test_helper.rb</tt>:</p>
|
501
|
+
<div class="code_container">
|
502
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
503
|
+
ActionController::TestCase.class_eval do
|
504
|
+
# save a reference to the original process method
|
505
|
+
alias_method :original_process, :process
|
506
|
+
|
507
|
+
# now redefine process and delegate to original_process
|
508
|
+
def process(action, params=nil, session=nil, flash=nil, http_method='GET')
|
509
|
+
params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
|
510
|
+
original_process(action, params, session, flash, http_method)
|
511
|
+
end
|
512
|
+
end
|
513
|
+
</pre>
|
514
|
+
</div>
|
515
|
+
<p>That’s the method <tt>get</tt>, <tt>post</tt>, etc., delegate the work to.</p>
|
516
|
+
<p>That technique has a risk, it could be the case that <tt>:original_process</tt> was taken. To try to avoid collisions people choose some label that characterizes what the chaining is about:</p>
|
517
|
+
<div class="code_container">
|
518
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
519
|
+
ActionController::TestCase.class_eval do
|
520
|
+
def process_with_stringified_params(...)
|
521
|
+
params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
|
522
|
+
process_without_stringified_params(action, params, session, flash, http_method)
|
523
|
+
end
|
524
|
+
alias_method :process_without_stringified_params, :process
|
525
|
+
alias_method :process, :process_with_stringified_params
|
526
|
+
end
|
527
|
+
</pre>
|
528
|
+
</div>
|
529
|
+
<p>The method <tt>alias_method_chain</tt> provides a shortcut for that pattern:</p>
|
530
|
+
<div class="code_container">
|
531
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
532
|
+
ActionController::TestCase.class_eval do
|
533
|
+
def process_with_stringified_params(...)
|
534
|
+
params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
|
535
|
+
process_without_stringified_params(action, params, session, flash, http_method)
|
536
|
+
end
|
537
|
+
alias_method_chain :process, :stringified_params
|
538
|
+
end
|
539
|
+
</pre>
|
540
|
+
</div>
|
541
|
+
<p>Rails uses <tt>alias_method_chain</tt> all over the code base. For example validations are added to <tt>ActiveRecord::Base#save</tt> by wrapping the method that way in a separate module specialized in validations.</p>
|
542
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/module/aliasing.rb</tt>.</p></div>
|
543
|
+
<h4 id="attributes">3.2 Attributes</h4>
|
544
|
+
<h5 id="alias_attribute">3.2.1 <tt>alias_attribute</tt></h5>
|
545
|
+
<p>Model attributes have a reader, a writer, and a predicate. You can alias a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (my mnemonic is they go in the same order as if you did an assignment):</p>
|
546
|
+
<div class="code_container">
|
547
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
548
|
+
class User < ActiveRecord::Base
|
549
|
+
# let me refer to the email column as "login",
|
550
|
+
# possibly meaningful for authentication code
|
551
|
+
alias_attribute :login, :email
|
552
|
+
end
|
553
|
+
</pre>
|
554
|
+
</div>
|
555
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/module/aliasing.rb</tt>.</p></div>
|
556
|
+
<h5 id="attr_accessor_with_default">3.2.2 <tt>attr_accessor_with_default</tt></h5>
|
557
|
+
<p>The method <tt>attr_accessor_with_default</tt> serves the same purpose as the Ruby macro <tt>attr_accessor</tt> but allows you to set a default value for the attribute:</p>
|
558
|
+
<div class="code_container">
|
559
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
560
|
+
class Url
|
561
|
+
attr_accessor_with_default :port, 80
|
562
|
+
end
|
563
|
+
|
564
|
+
Url.new.port # => 80
|
565
|
+
</pre>
|
566
|
+
</div>
|
567
|
+
<p>The default value can be also specified with a block, which is called in the context of the corresponding object:</p>
|
568
|
+
<div class="code_container">
|
569
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
570
|
+
class User
|
571
|
+
attr_accessor :name, :surname
|
572
|
+
attr_accessor_with_default(:full_name) do
|
573
|
+
[name, surname].compact.join(" ")
|
574
|
+
end
|
575
|
+
end
|
576
|
+
|
577
|
+
u = User.new
|
578
|
+
u.name = 'Xavier'
|
579
|
+
u.surname = 'Noria'
|
580
|
+
u.full_name # => "Xavier Noria"
|
581
|
+
</pre>
|
582
|
+
</div>
|
583
|
+
<p>The result is not cached, the block is invoked in each call to the reader.</p>
|
584
|
+
<p>You can overwrite the default with the writer:</p>
|
585
|
+
<div class="code_container">
|
586
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
587
|
+
url = Url.new
|
588
|
+
url.host # => 80
|
589
|
+
url.host = 8080
|
590
|
+
url.host # => 8080
|
591
|
+
</pre>
|
592
|
+
</div>
|
593
|
+
<p>The default value is returned as long as the attribute is unset. The reader does not rely on the value of the attribute to know whether it has to return the default. It rather monitors the writer: if there’s any assignment the value is no longer considered to be unset.</p>
|
594
|
+
<p>Active Resource uses this macro to set a default value for the <tt>:primary_key</tt> attribute:</p>
|
595
|
+
<div class="code_container">
|
596
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
597
|
+
attr_accessor_with_default :primary_key, 'id'
|
598
|
+
</pre>
|
599
|
+
</div>
|
600
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/module/attr_accessor_with_default.rb</tt>.</p></div>
|
601
|
+
<h5 id="internal-attributes">3.2.3 Internal Attributes</h5>
|
602
|
+
<p>When you are defining an attribute in a class that is meant to be subclassed name collisions are a risk. That’s remarkably important for libraries.</p>
|
603
|
+
<p>Active Support defines the macros <tt>attr_internal_reader</tt>, <tt>attr_internal_writer</tt>, and <tt>attr_internal_accessor</tt>. They behave like their Ruby built-in <tt>attr_*</tt> counterparts, except they name the underlying instance variable in a way that makes collisions less likely.</p>
|
604
|
+
<p>The macro <tt>attr_internal</tt> is a synonym for <tt>attr_internal_accessor</tt>:</p>
|
605
|
+
<div class="code_container">
|
606
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
607
|
+
# library
|
608
|
+
class ThirdPartyLibrary::Crawler
|
609
|
+
attr_internal :log_level
|
610
|
+
end
|
611
|
+
|
612
|
+
# client code
|
613
|
+
class MyCrawler < ThirdPartyLibrary::Crawler
|
614
|
+
attr_accessor :log_level
|
615
|
+
end
|
616
|
+
</pre>
|
617
|
+
</div>
|
618
|
+
<p>In the previous example it could be the case that <tt>:log_level</tt> does not belong to the public interface of the library and it is only used for development. The client code, unaware of the potential conflict, subclasses and defines its own <tt>:log_level</tt>. Thanks to <tt>attr_internal</tt> there’s no collision.</p>
|
619
|
+
<p>By default the internal instance variable is named with a leading underscore, <tt>@_log_level</tt> in the example above. That’s configurable via <tt>Module.attr_internal_naming_format</tt> though, you can pass any <tt>sprintf</tt>-like format string with a leading <tt>@</tt> and a <tt>%s</tt> somewhere, which is where the name will be placed. The default is <tt>"@_%s"</tt>.</p>
|
620
|
+
<p>Rails uses internal attributes in a few spots, for examples for views:</p>
|
621
|
+
<div class="code_container">
|
622
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
623
|
+
module ActionView
|
624
|
+
class Base
|
625
|
+
attr_internal :captures
|
626
|
+
attr_internal :request, :layout
|
627
|
+
attr_internal :controller, :template
|
628
|
+
end
|
629
|
+
end
|
630
|
+
</pre>
|
631
|
+
</div>
|
632
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/module/attr_internal.rb</tt>.</p></div>
|
633
|
+
<h5 id="module-attributes">3.2.4 Module Attributes</h5>
|
634
|
+
<p>The macros <tt>mattr_reader</tt>, <tt>mattr_writer</tt>, and <tt>mattr_accessor</tt> are analogous to the <tt>cattr_*</tt> macros defined for class. Check <a href="#class-attributes">Class Attributes</a>.</p>
|
635
|
+
<p>For example, the dependencies mechanism uses them:</p>
|
636
|
+
<div class="code_container">
|
637
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
638
|
+
module ActiveSupport
|
639
|
+
module Dependencies
|
640
|
+
mattr_accessor :warnings_on_first_load
|
641
|
+
mattr_accessor :history
|
642
|
+
mattr_accessor :loaded
|
643
|
+
mattr_accessor :mechanism
|
644
|
+
mattr_accessor :load_paths
|
645
|
+
mattr_accessor :load_once_paths
|
646
|
+
mattr_accessor :autoloaded_constants
|
647
|
+
mattr_accessor :explicitly_unloadable_constants
|
648
|
+
mattr_accessor :logger
|
649
|
+
mattr_accessor :log_activity
|
650
|
+
mattr_accessor :constant_watch_stack
|
651
|
+
mattr_accessor :constant_watch_stack_mutex
|
652
|
+
end
|
653
|
+
end
|
654
|
+
</pre>
|
655
|
+
</div>
|
656
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/module/attribute_accessors.rb</tt>.</p></div>
|
657
|
+
<h4 id="parents">3.3 Parents</h4>
|
658
|
+
<h5 id="parent">3.3.1 <tt>parent</tt></h5>
|
659
|
+
<p>The <tt>parent</tt> method on a nested named module returns the module that contains its corresponding constant:</p>
|
660
|
+
<div class="code_container">
|
661
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
662
|
+
module X
|
663
|
+
module Y
|
664
|
+
module Z
|
665
|
+
end
|
666
|
+
end
|
667
|
+
end
|
668
|
+
M = X::Y::Z
|
669
|
+
|
670
|
+
X::Y::Z.parent # => X::Y
|
671
|
+
M.parent # => X::Y
|
672
|
+
</pre>
|
673
|
+
</div>
|
674
|
+
<p>If the module is anonymous or belongs to the top-level, <tt>parent</tt> returns <tt>Object</tt>.</p>
|
675
|
+
<div class="warning"><p>Note that in that case <tt>parent_name</tt> returns <tt>nil</tt>.</p></div>
|
676
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/module/introspection.rb</tt>.</p></div>
|
677
|
+
<h5 id="parent_name">3.3.2 <tt>parent_name</tt></h5>
|
678
|
+
<p>The <tt>parent_name</tt> method on a nested named module returns the fully-qualified name of the module that contains its corresponding constant:</p>
|
679
|
+
<div class="code_container">
|
680
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
681
|
+
module X
|
682
|
+
module Y
|
683
|
+
module Z
|
684
|
+
end
|
685
|
+
end
|
686
|
+
end
|
687
|
+
M = X::Y::Z
|
688
|
+
|
689
|
+
X::Y::Z.parent_name # => "X::Y"
|
690
|
+
M.parent_name # => "X::Y"
|
691
|
+
</pre>
|
692
|
+
</div>
|
693
|
+
<p>For top-level or anonymous modules <tt>parent_name</tt> returns <tt>nil</tt>.</p>
|
694
|
+
<div class="warning"><p>Note that in that case <tt>parent</tt> returns <tt>Object</tt>.</p></div>
|
695
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/module/introspection.rb</tt>.</p></div>
|
696
|
+
<h5 id="module-parents">3.3.3 <tt>parents</tt></h5>
|
697
|
+
<p>The method <tt>parents</tt> calls <tt>parent</tt> on the receiver and upwards until <tt>Object</tt> is reached. The chain is returned in an array, from bottom to top:</p>
|
698
|
+
<div class="code_container">
|
699
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
700
|
+
module X
|
701
|
+
module Y
|
702
|
+
module Z
|
703
|
+
end
|
704
|
+
end
|
705
|
+
end
|
706
|
+
M = X::Y::Z
|
707
|
+
|
708
|
+
X::Y::Z.parents # => [X::Y, X, Object]
|
709
|
+
M.parents # => [X::Y, X, Object]
|
710
|
+
</pre>
|
711
|
+
</div>
|
712
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/module/introspection.rb</tt>.</p></div>
|
713
|
+
<h4 id="constants">3.4 Constants</h4>
|
714
|
+
<p>The method <tt>local_constants</tt> returns the names of the constants that have been defined in the receiver module:</p>
|
715
|
+
<div class="code_container">
|
716
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
717
|
+
module X
|
718
|
+
X1 = 1
|
719
|
+
X2 = 2
|
720
|
+
module Y
|
721
|
+
Y1 = :y1
|
722
|
+
X1 = :overrides_X1_above
|
723
|
+
end
|
724
|
+
end
|
725
|
+
|
726
|
+
X.local_constants # => ["X2", "X1", "Y"], assumes Ruby 1.8
|
727
|
+
X::Y.local_constants # => ["X1", "Y1"], assumes Ruby 1.8
|
728
|
+
</pre>
|
729
|
+
</div>
|
730
|
+
<p>The names are returned as strings in Ruby 1.8, and as symbols in Ruby 1.9. The method <tt>local_constant_names</tt> always returns strings.</p>
|
731
|
+
<div class="warning"><p>This method returns precise results in Ruby 1.9. In older versions of Ruby, however, it may miss some constants in case the same constant exists in the receiver module as well as in any of its ancestors and both constants point to the same object (objects are compared using <tt>Object#object_id</tt>).</p></div>
|
732
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/module/introspection.rb</tt>.</p></div>
|
733
|
+
<h5 id="qualified-constant-names">3.4.1 Qualified Constant Names</h5>
|
734
|
+
<p>The standard methods <tt>const_defined?</tt>, <tt>const_get</tt> , and <tt>const_set</tt> accept
|
735
|
+
bare constant names. Active Support extends this <span class="caps">API</span> to be able to pass
|
736
|
+
relative qualified constant names.</p>
|
737
|
+
<p>The new methods are <tt>qualified_const_defined?</tt>, <tt>qualified_const_get</tt>, and
|
738
|
+
<tt>qualified_const_set</tt>. Their arguments are assumed to be qualified constant
|
739
|
+
names relative to their receiver:</p>
|
740
|
+
<div class="code_container">
|
741
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
742
|
+
Object.qualified_const_defined?("Math::PI") # => true
|
743
|
+
Object.qualified_const_get("Math::PI") # => 3.141592653589793
|
744
|
+
Object.qualified_const_set("Math::Phi", 1.618034) # => 1.618034
|
745
|
+
</pre>
|
746
|
+
</div>
|
747
|
+
<p>Arguments may be bare constant names:</p>
|
748
|
+
<div class="code_container">
|
749
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
750
|
+
Math.qualified_const_get("E") # => 2.718281828459045
|
751
|
+
</pre>
|
752
|
+
</div>
|
753
|
+
<p>These methods are analogous to their builtin counterparts. In particular,
|
754
|
+
<tt>qualified_constant_defined?</tt> accepts an optional second argument in 1.9
|
755
|
+
to be able to say whether you want the predicate to look in the ancestors.
|
756
|
+
This flag is taken into account for each constant in the expression while
|
757
|
+
walking down the path.</p>
|
758
|
+
<p>For example, given</p>
|
759
|
+
<div class="code_container">
|
760
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
761
|
+
module M
|
762
|
+
X = 1
|
763
|
+
end
|
764
|
+
|
765
|
+
module N
|
766
|
+
class C
|
767
|
+
include M
|
768
|
+
end
|
769
|
+
end
|
770
|
+
</pre>
|
771
|
+
</div>
|
772
|
+
<p><tt>qualified_const_defined?</tt> behaves this way:</p>
|
773
|
+
<div class="code_container">
|
774
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
775
|
+
N.qualified_const_defined?("C::X", false) # => false (1.9 only)
|
776
|
+
N.qualified_const_defined?("C::X", true) # => true (1.9 only)
|
777
|
+
N.qualified_const_defined?("C::X") # => false in 1.8, true in 1.9
|
778
|
+
</pre>
|
779
|
+
</div>
|
780
|
+
<p>As the last example implies, in 1.9 the second argument defaults to true,
|
781
|
+
as in <tt>const_defined?</tt>.</p>
|
782
|
+
<p>For coherence with the builtin methods only relative paths are accepted.
|
783
|
+
Absolute qualified constant names like <tt>::Math::PI</tt> raise <tt>NameError</tt>.</p>
|
784
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/module/qualified_const.rb</tt>.</p></div>
|
785
|
+
<h4 id="synchronization">3.5 Synchronization</h4>
|
786
|
+
<p>The <tt>synchronize</tt> macro declares a method to be synchronized:</p>
|
787
|
+
<div class="code_container">
|
788
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
789
|
+
class Counter
|
790
|
+
@@mutex = Mutex.new
|
791
|
+
attr_reader :value
|
792
|
+
|
793
|
+
def initialize
|
794
|
+
@value = 0
|
795
|
+
end
|
796
|
+
|
797
|
+
def incr
|
798
|
+
@value += 1 # non-atomic
|
799
|
+
end
|
800
|
+
synchronize :incr, :with => '@@mutex'
|
801
|
+
end
|
802
|
+
</pre>
|
803
|
+
</div>
|
804
|
+
<p>The method receives the name of an action, and a <tt>:with</tt> option with code. The code is evaluated in the context of the receiver each time the method is invoked, and it should evaluate to a <tt>Mutex</tt> instance or any other object that responds to <tt>synchronize</tt> and accepts a block.</p>
|
805
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/module/synchronization.rb</tt>.</p></div>
|
806
|
+
<h4 id="reachable">3.6 Reachable</h4>
|
807
|
+
<p>A named module is reachable if it is stored in its corresponding constant. It means you can reach the module object via the constant.</p>
|
808
|
+
<p>That is what ordinarily happens, if a module is called “M”, the <tt>M</tt> constant exists and holds it:</p>
|
809
|
+
<div class="code_container">
|
810
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
811
|
+
module M
|
812
|
+
end
|
813
|
+
|
814
|
+
M.reachable? # => true
|
815
|
+
</pre>
|
816
|
+
</div>
|
817
|
+
<p>But since constants and modules are indeed kind of decoupled, module objects can become unreachable:</p>
|
818
|
+
<div class="code_container">
|
819
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
820
|
+
module M
|
821
|
+
end
|
822
|
+
|
823
|
+
orphan = Object.send(:remove_const, :M)
|
824
|
+
|
825
|
+
# The module object is orphan now but it still has a name.
|
826
|
+
orphan.name # => "M"
|
827
|
+
|
828
|
+
# You cannot reach it via the constant M because it does not even exist.
|
829
|
+
orphan.reachable? # => false
|
830
|
+
|
831
|
+
# Let's define a module called "M" again.
|
832
|
+
module M
|
833
|
+
end
|
834
|
+
|
835
|
+
# The constant M exists now again, and it stores a module
|
836
|
+
# object called "M", but it is a new instance.
|
837
|
+
orphan.reachable? # => false
|
838
|
+
</pre>
|
839
|
+
</div>
|
840
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/module/reachable.rb</tt>.</p></div>
|
841
|
+
<h4 id="anonymous">3.7 Anonymous</h4>
|
842
|
+
<p>A module may or may not have a name:</p>
|
843
|
+
<div class="code_container">
|
844
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
845
|
+
module M
|
846
|
+
end
|
847
|
+
M.name # => "M"
|
848
|
+
|
849
|
+
N = Module.new
|
850
|
+
N.name # => "N"
|
851
|
+
|
852
|
+
Module.new.name # => "" in 1.8, nil in 1.9
|
853
|
+
</pre>
|
854
|
+
</div>
|
855
|
+
<p>You can check whether a module has a name with the predicate <tt>anonymous?</tt>:</p>
|
856
|
+
<div class="code_container">
|
857
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
858
|
+
module M
|
859
|
+
end
|
860
|
+
M.anonymous? # => false
|
861
|
+
|
862
|
+
Module.new.anonymous? # => true
|
863
|
+
</pre>
|
864
|
+
</div>
|
865
|
+
<p>Note that being unreachable does not imply being anonymous:</p>
|
866
|
+
<div class="code_container">
|
867
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
868
|
+
module M
|
869
|
+
end
|
870
|
+
|
871
|
+
m = Object.send(:remove_const, :M)
|
872
|
+
|
873
|
+
m.reachable? # => false
|
874
|
+
m.anonymous? # => false
|
875
|
+
</pre>
|
876
|
+
</div>
|
877
|
+
<p>though an anonymous module is unreachable by definition.</p>
|
878
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/module/anonymous.rb</tt>.</p></div>
|
879
|
+
<h4 id="method-delegation">3.8 Method Delegation</h4>
|
880
|
+
<p>The macro <tt>delegate</tt> offers an easy way to forward methods.</p>
|
881
|
+
<p>Let’s imagine that users in some application have login information in the <tt>User</tt> model but name and other data in a separate <tt>Profile</tt> model:</p>
|
882
|
+
<div class="code_container">
|
883
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
884
|
+
class User < ActiveRecord::Base
|
885
|
+
has_one :profile
|
886
|
+
end
|
887
|
+
</pre>
|
888
|
+
</div>
|
889
|
+
<p>With that configuration you get a user’s name via his profile, <tt>user.profile.name</tt>, but it could be handy to still be able to access such attribute directly:</p>
|
890
|
+
<div class="code_container">
|
891
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
892
|
+
class User < ActiveRecord::Base
|
893
|
+
has_one :profile
|
894
|
+
|
895
|
+
def name
|
896
|
+
profile.name
|
897
|
+
end
|
898
|
+
end
|
899
|
+
</pre>
|
900
|
+
</div>
|
901
|
+
<p>That is what <tt>delegate</tt> does for you:</p>
|
902
|
+
<div class="code_container">
|
903
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
904
|
+
class User < ActiveRecord::Base
|
905
|
+
has_one :profile
|
906
|
+
|
907
|
+
delegate :name, :to => :profile
|
908
|
+
end
|
909
|
+
</pre>
|
910
|
+
</div>
|
911
|
+
<p>It is shorter, and the intention more obvious.</p>
|
912
|
+
<p>The method must be public in the target.</p>
|
913
|
+
<p>The <tt>delegate</tt> macro accepts several methods:</p>
|
914
|
+
<div class="code_container">
|
915
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
916
|
+
delegate :name, :age, :address, :twitter, :to => :profile
|
917
|
+
</pre>
|
918
|
+
</div>
|
919
|
+
<p>When interpolated into a string, the <tt>:to</tt> option should become an expression that evaluates to the object the method is delegated to. Typically a string or symbol. Such an expression is evaluated in the context of the receiver:</p>
|
920
|
+
<div class="code_container">
|
921
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
922
|
+
# delegates to the Rails constant
|
923
|
+
delegate :logger, :to => :Rails
|
924
|
+
|
925
|
+
# delegates to the receiver's class
|
926
|
+
delegate :table_name, :to => 'self.class'
|
927
|
+
</pre>
|
928
|
+
</div>
|
929
|
+
<div class="warning"><p>If the <tt>:prefix</tt> option is <tt>true</tt> this is less generic, see below.</p></div>
|
930
|
+
<p>By default, if the delegation raises <tt>NoMethodError</tt> and the target is <tt>nil</tt> the exception is propagated. You can ask that <tt>nil</tt> is returned instead with the <tt>:allow_nil</tt> option:</p>
|
931
|
+
<div class="code_container">
|
932
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
933
|
+
delegate :name, :to => :profile, :allow_nil => true
|
934
|
+
</pre>
|
935
|
+
</div>
|
936
|
+
<p>With <tt>:allow_nil</tt> the call <tt>user.name</tt> returns <tt>nil</tt> if the user has no profile.</p>
|
937
|
+
<p>The option <tt>:prefix</tt> adds a prefix to the name of the generated method. This may be handy for example to get a better name:</p>
|
938
|
+
<div class="code_container">
|
939
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
940
|
+
delegate :street, :to => :address, :prefix => true
|
941
|
+
</pre>
|
942
|
+
</div>
|
943
|
+
<p>The previous example generates <tt>address_street</tt> rather than <tt>street</tt>.</p>
|
944
|
+
<div class="warning"><p>Since in this case the name of the generated method is composed of the target object and target method names, the <tt>:to</tt> option must be a method name.</p></div>
|
945
|
+
<p>A custom prefix may also be configured:</p>
|
946
|
+
<div class="code_container">
|
947
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
948
|
+
delegate :size, :to => :attachment, :prefix => :avatar
|
949
|
+
</pre>
|
950
|
+
</div>
|
951
|
+
<p>In the previous example the macro generates <tt>avatar_size</tt> rather than <tt>size</tt>.</p>
|
952
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/module/delegation.rb</tt></p></div>
|
953
|
+
<h4 id="method-names">3.9 Method Names</h4>
|
954
|
+
<p>The builtin methods <tt>instance_methods</tt> and <tt>methods</tt> return method names as strings or symbols depending on the Ruby version. Active Support defines <tt>instance_method_names</tt> and <tt>method_names</tt> to be equivalent to them, respectively, but always getting strings back.</p>
|
955
|
+
<p>For example, <tt>ActionView::Helpers::FormBuilder</tt> knows this array difference is going to work no matter the Ruby version:</p>
|
956
|
+
<div class="code_container">
|
957
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
958
|
+
self.field_helpers = (FormHelper.instance_method_names - ['form_for'])
|
959
|
+
</pre>
|
960
|
+
</div>
|
961
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/module/method_names.rb</tt></p></div>
|
962
|
+
<h4 id="redefining-methods">3.10 Redefining Methods</h4>
|
963
|
+
<p>There are cases where you need to define a method with <tt>define_method</tt>, but don’t know whether a method with that name already exists. If it does, a warning is issued if they are enabled. No big deal, but not clean either.</p>
|
964
|
+
<p>The method <tt>redefine_method</tt> prevents such a potential warning, removing the existing method before if needed. Rails uses it in a few places, for instance when it generates an association’s <span class="caps">API</span>:</p>
|
965
|
+
<div class="code_container">
|
966
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
967
|
+
redefine_method("#{reflection.name}=") do |new_value|
|
968
|
+
association = association_instance_get(reflection.name)
|
969
|
+
|
970
|
+
if association.nil? || association.target != new_value
|
971
|
+
association = association_proxy_class.new(self, reflection)
|
972
|
+
end
|
973
|
+
|
974
|
+
association.replace(new_value)
|
975
|
+
association_instance_set(reflection.name, new_value.nil? ? nil : association)
|
976
|
+
end
|
977
|
+
</pre>
|
978
|
+
</div>
|
979
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/module/remove_method.rb</tt></p></div>
|
980
|
+
<h3 id="extensions-to-class">4 Extensions to <tt>Class</tt></h3>
|
981
|
+
<h4 id="class-attributes">4.1 Class Attributes</h4>
|
982
|
+
<h5 id="class_attribute">4.1.1 <tt>class_attribute</tt></h5>
|
983
|
+
<p>The method <tt>class_attribute</tt> declares one or more inheritable class attributes that can be overridden at any level down the hierarchy.</p>
|
984
|
+
<div class="code_container">
|
985
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
986
|
+
class A
|
987
|
+
class_attribute :x
|
988
|
+
end
|
989
|
+
|
990
|
+
class B < A; end
|
991
|
+
|
992
|
+
class C < B; end
|
993
|
+
|
994
|
+
A.x = :a
|
995
|
+
B.x # => :a
|
996
|
+
C.x # => :a
|
997
|
+
|
998
|
+
B.x = :b
|
999
|
+
A.x # => :a
|
1000
|
+
C.x # => :b
|
1001
|
+
|
1002
|
+
C.x = :c
|
1003
|
+
A.x # => :a
|
1004
|
+
B.x # => :b
|
1005
|
+
</pre>
|
1006
|
+
</div>
|
1007
|
+
<p>For example <tt>ActionMailer::Base</tt> defines:</p>
|
1008
|
+
<div class="code_container">
|
1009
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1010
|
+
class_attribute :default_params
|
1011
|
+
self.default_params = {
|
1012
|
+
:mime_version => "1.0",
|
1013
|
+
:charset => "UTF-8",
|
1014
|
+
:content_type => "text/plain",
|
1015
|
+
:parts_order => [ "text/plain", "text/enriched", "text/html" ]
|
1016
|
+
}.freeze
|
1017
|
+
</pre>
|
1018
|
+
</div>
|
1019
|
+
<p>They can be also accessed and overridden at the instance level.</p>
|
1020
|
+
<div class="code_container">
|
1021
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1022
|
+
A.x = 1
|
1023
|
+
|
1024
|
+
a1 = A.new
|
1025
|
+
a2 = A.new
|
1026
|
+
a2.x = 2
|
1027
|
+
|
1028
|
+
a1.x # => 1, comes from A
|
1029
|
+
a2.x # => 2, overridden in a2
|
1030
|
+
</pre>
|
1031
|
+
</div>
|
1032
|
+
<p>The generation of the writer instance method can be prevented by setting the option <tt>:instance_writer</tt> to <tt>false</tt>.</p>
|
1033
|
+
<div class="code_container">
|
1034
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1035
|
+
module ActiveRecord
|
1036
|
+
class Base
|
1037
|
+
class_attribute :table_name_prefix, :instance_writer => false
|
1038
|
+
self.table_name_prefix = ""
|
1039
|
+
end
|
1040
|
+
end
|
1041
|
+
</pre>
|
1042
|
+
</div>
|
1043
|
+
<p>A model may find that option useful as a way to prevent mass-assignment from setting the attribute.</p>
|
1044
|
+
<p>The generation of the reader instance method can be prevented by setting the option <tt>:instance_reader</tt> to <tt>false</tt>.</p>
|
1045
|
+
<div class="code_container">
|
1046
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1047
|
+
class A
|
1048
|
+
class_attribute :x, :instance_reader => false
|
1049
|
+
end
|
1050
|
+
|
1051
|
+
A.new.x = 1 # NoMethodError
|
1052
|
+
</pre>
|
1053
|
+
</div>
|
1054
|
+
<p>For convenience <tt>class_attribute</tt> also defines an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called <tt>x?</tt>.</p>
|
1055
|
+
<p>When <tt>:instance_reader</tt> is <tt>false</tt>, the instance predicate returns a <tt>NoMethodError</tt> just like the reader method.</p>
|
1056
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/class/attribute.rb</tt></p></div>
|
1057
|
+
<h5 id="cattr_reader-cattr_writer-and-cattr_accessor">4.1.2 <tt>cattr_reader</tt>, <tt>cattr_writer</tt>, and <tt>cattr_accessor</tt></h5>
|
1058
|
+
<p>The macros <tt>cattr_reader</tt>, <tt>cattr_writer</tt>, and <tt>cattr_accessor</tt> are analogous to their <tt>attr_*</tt> counterparts but for classes. They initialize a class variable to <tt>nil</tt> unless it already exists, and generate the corresponding class methods to access it:</p>
|
1059
|
+
<div class="code_container">
|
1060
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1061
|
+
class MysqlAdapter < AbstractAdapter
|
1062
|
+
# Generates class methods to access @@emulate_booleans.
|
1063
|
+
cattr_accessor :emulate_booleans
|
1064
|
+
self.emulate_booleans = true
|
1065
|
+
end
|
1066
|
+
</pre>
|
1067
|
+
</div>
|
1068
|
+
<p>Instance methods are created as well for convenience, they are just proxies to the class attribute. So, instances can change the class attribute, but cannot override it as it happens with <tt>class_attribute</tt> (see above). For example given</p>
|
1069
|
+
<div class="code_container">
|
1070
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1071
|
+
module ActionView
|
1072
|
+
class Base
|
1073
|
+
cattr_accessor :field_error_proc
|
1074
|
+
@@field_error_proc = Proc.new{ ... }
|
1075
|
+
end
|
1076
|
+
end
|
1077
|
+
</pre>
|
1078
|
+
</div>
|
1079
|
+
<p>we can access <tt>field_error_proc</tt> in views.</p>
|
1080
|
+
<p>The generation of the reader instance method can be prevented by setting <tt>:instance_reader</tt> to <tt>false</tt> and the generation of the writer instance method can be prevented by setting <tt>:instance_writer</tt> to <tt>false</tt>. Generation of both methods can be prevented by setting <tt>:instance_accessor</tt> to <tt>false</tt>. In all cases, the value must be exactly <tt>false</tt> and not any false value.</p>
|
1081
|
+
<div class="code_container">
|
1082
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1083
|
+
module A
|
1084
|
+
class B
|
1085
|
+
# No first_name instance reader is generated.
|
1086
|
+
cattr_accessor :first_name, :instance_reader => false
|
1087
|
+
# No last_name= instance writer is generated.
|
1088
|
+
cattr_accessor :last_name, :instance_writer => false
|
1089
|
+
# No surname instance reader or surname= writer is generated.
|
1090
|
+
cattr_accessor :surname, :instance_accessor => false
|
1091
|
+
end
|
1092
|
+
end
|
1093
|
+
</pre>
|
1094
|
+
</div>
|
1095
|
+
<p>A model may find it useful to set <tt>:instance_accessor</tt> to <tt>false</tt> as a way to prevent mass-assignment from setting the attribute.</p>
|
1096
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/class/attribute_accessors.rb</tt>.</p></div>
|
1097
|
+
<h4 id="class-inheritable-attributes">4.2 Class Inheritable Attributes</h4>
|
1098
|
+
<div class="warning"><p>Class Inheritable Attributes are deprecated. It’s recommended that you use <tt>Class#class_attribute</tt> instead.</p></div>
|
1099
|
+
<p>Class variables are shared down the inheritance tree. Class instance variables are not shared, but they are not inherited either. The macros <tt>class_inheritable_reader</tt>, <tt>class_inheritable_writer</tt>, and <tt>class_inheritable_accessor</tt> provide accessors for class-level data which is inherited but not shared with children:</p>
|
1100
|
+
<div class="code_container">
|
1101
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1102
|
+
module ActionController
|
1103
|
+
class Base
|
1104
|
+
# FIXME: REVISE/SIMPLIFY THIS COMMENT.
|
1105
|
+
# The value of allow_forgery_protection is inherited,
|
1106
|
+
# but its value in a particular class does not affect
|
1107
|
+
# the value in the rest of the controllers hierarchy.
|
1108
|
+
class_inheritable_accessor :allow_forgery_protection
|
1109
|
+
end
|
1110
|
+
end
|
1111
|
+
</pre>
|
1112
|
+
</div>
|
1113
|
+
<p>They accomplish this with class instance variables and cloning on subclassing, there are no class variables involved. Cloning is performed with <tt>dup</tt> as long as the value is duplicable.</p>
|
1114
|
+
<p>There are some variants specialised in arrays and hashes:</p>
|
1115
|
+
<div class="code_container">
|
1116
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1117
|
+
class_inheritable_array
|
1118
|
+
class_inheritable_hash
|
1119
|
+
</pre>
|
1120
|
+
</div>
|
1121
|
+
<p>Those writers take any inherited array or hash into account and extend them rather than overwrite them.</p>
|
1122
|
+
<p>As with vanilla class attribute accessors these macros create convenience instance methods for reading and writing. The generation of the writer instance method can be prevented setting <tt>:instance_writer</tt> to <tt>false</tt> (not any false value, but exactly <tt>false</tt>):</p>
|
1123
|
+
<div class="code_container">
|
1124
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1125
|
+
module ActiveRecord
|
1126
|
+
class Base
|
1127
|
+
class_inheritable_accessor :default_scoping, :instance_writer => false
|
1128
|
+
end
|
1129
|
+
end
|
1130
|
+
</pre>
|
1131
|
+
</div>
|
1132
|
+
<p>Since values are copied when a subclass is defined, if the base class changes the attribute after that, the subclass does not see the new value. That’s the point.</p>
|
1133
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/class/inheritable_attributes.rb</tt>.</p></div>
|
1134
|
+
<h4 id="subclasses-descendants">4.3 Subclasses & Descendants</h4>
|
1135
|
+
<h5 id="subclasses">4.3.1 <tt>subclasses</tt></h5>
|
1136
|
+
<p>The <tt>subclasses</tt> method returns the subclasses of the receiver:</p>
|
1137
|
+
<div class="code_container">
|
1138
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1139
|
+
class C; end
|
1140
|
+
C.subclasses # => []
|
1141
|
+
|
1142
|
+
class B < C; end
|
1143
|
+
C.subclasses # => [B]
|
1144
|
+
|
1145
|
+
class A < B; end
|
1146
|
+
C.subclasses # => [B]
|
1147
|
+
|
1148
|
+
class D < C; end
|
1149
|
+
C.subclasses # => [B, D]
|
1150
|
+
</pre>
|
1151
|
+
</div>
|
1152
|
+
<p>The order in which these classes are returned is unspecified.</p>
|
1153
|
+
<div class="warning"><p>This method is redefined in some Rails core classes but should be all compatible in Rails 3.1.</p></div>
|
1154
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/class/subclasses.rb</tt>.</p></div>
|
1155
|
+
<h5 id="descendants">4.3.2 <tt>descendants</tt></h5>
|
1156
|
+
<p>The <tt>descendants</tt> method returns all classes that are <tt><</tt> than its receiver:</p>
|
1157
|
+
<div class="code_container">
|
1158
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1159
|
+
class C; end
|
1160
|
+
C.descendants # => []
|
1161
|
+
|
1162
|
+
class B < C; end
|
1163
|
+
C.descendants # => [B]
|
1164
|
+
|
1165
|
+
class A < B; end
|
1166
|
+
C.descendants # => [B, A]
|
1167
|
+
|
1168
|
+
class D < C; end
|
1169
|
+
C.descendants # => [B, A, D]
|
1170
|
+
</pre>
|
1171
|
+
</div>
|
1172
|
+
<p>The order in which these classes are returned is unspecified.</p>
|
1173
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/class/subclasses.rb</tt>.</p></div>
|
1174
|
+
<h3 id="extensions-to-string">5 Extensions to <tt>String</tt></h3>
|
1175
|
+
<h4 id="output-safety">5.1 Output Safety</h4>
|
1176
|
+
<h5 id="motivation">5.1.1 Motivation</h5>
|
1177
|
+
<p>Inserting data into <span class="caps">HTML</span> templates needs extra care. For example you can’t just interpolate <tt>@review.title</tt> verbatim into an <span class="caps">HTML</span> page. On one hand if the review title is “Flanagan & Matz rules!” the output won’t be well-formed because an ampersand has to be escaped as “&amp;”. On the other hand, depending on the application that may be a big security hole because users can inject malicious <span class="caps">HTML</span> setting a hand-crafted review title. Check out the <a href="security.html#cross-site-scripting-xss">section about cross-site scripting in the Security guide</a> for further information about the risks.</p>
|
1178
|
+
<h5 id="safe-strings">5.1.2 Safe Strings</h5>
|
1179
|
+
<p>Active Support has the concept of <i>(html) safe</i> strings since Rails 3. A safe string is one that is marked as being insertable into <span class="caps">HTML</span> as is. It is trusted, no matter whether it has been escaped or not.</p>
|
1180
|
+
<p>Strings are considered to be <i>unsafe</i> by default:</p>
|
1181
|
+
<div class="code_container">
|
1182
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1183
|
+
"".html_safe? # => false
|
1184
|
+
</pre>
|
1185
|
+
</div>
|
1186
|
+
<p>You can obtain a safe string from a given one with the <tt>html_safe</tt> method:</p>
|
1187
|
+
<div class="code_container">
|
1188
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1189
|
+
s = "".html_safe
|
1190
|
+
s.html_safe? # => true
|
1191
|
+
</pre>
|
1192
|
+
</div>
|
1193
|
+
<p>It is important to understand that <tt>html_safe</tt> performs no escaping whatsoever, it is just an assertion:</p>
|
1194
|
+
<div class="code_container">
|
1195
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1196
|
+
s = "<script>...</script>".html_safe
|
1197
|
+
s.html_safe? # => true
|
1198
|
+
s # => "<script>...</script>"
|
1199
|
+
</pre>
|
1200
|
+
</div>
|
1201
|
+
<p>It is your responsibility to ensure calling <tt>html_safe</tt> on a particular string is fine.</p>
|
1202
|
+
<p>If you append onto a safe string, either in-place with <tt>concat</tt>/<tt><<</tt>, or with <tt>+</tt>, the result is a safe string. Unsafe arguments are escaped:</p>
|
1203
|
+
<div class="code_container">
|
1204
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1205
|
+
"".html_safe + "<" # => "&lt;"
|
1206
|
+
</pre>
|
1207
|
+
</div>
|
1208
|
+
<p>Safe arguments are directly appended:</p>
|
1209
|
+
<div class="code_container">
|
1210
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1211
|
+
"".html_safe + "<".html_safe # => "<"
|
1212
|
+
</pre>
|
1213
|
+
</div>
|
1214
|
+
<p>These methods should not be used in ordinary views. In Rails 3 unsafe values are automatically escaped:</p>
|
1215
|
+
<div class="code_container">
|
1216
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
1217
|
+
<%= @review.title %> <%# fine in Rails 3, escaped if needed %>
|
1218
|
+
</pre>
|
1219
|
+
</div>
|
1220
|
+
<p>To insert something verbatim use the <tt>raw</tt> helper rather than calling <tt>html_safe</tt>:</p>
|
1221
|
+
<div class="code_container">
|
1222
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
1223
|
+
<%= raw @cms.current_template %> <%# inserts @cms.current_template as is %>
|
1224
|
+
</pre>
|
1225
|
+
</div>
|
1226
|
+
<p>or, equivalently, use <tt><%==</tt>:</p>
|
1227
|
+
<div class="code_container">
|
1228
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
1229
|
+
<%== @cms.current_template %> <%# inserts @cms.current_template as is %>
|
1230
|
+
</pre>
|
1231
|
+
</div>
|
1232
|
+
<p>The <tt>raw</tt> helper calls <tt>html_safe</tt> for you:</p>
|
1233
|
+
<div class="code_container">
|
1234
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1235
|
+
def raw(stringish)
|
1236
|
+
stringish.to_s.html_safe
|
1237
|
+
end
|
1238
|
+
</pre>
|
1239
|
+
</div>
|
1240
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/output_safety.rb</tt>.</p></div>
|
1241
|
+
<h5 id="transformation">5.1.3 Transformation</h5>
|
1242
|
+
<p>As a rule of thumb, except perhaps for concatenation as explained above, any method that may change a string gives you an unsafe string. These are <tt>donwcase</tt>, <tt>gsub</tt>, <tt>strip</tt>, <tt>chomp</tt>, <tt>underscore</tt>, etc.</p>
|
1243
|
+
<p>In the case of in-place transformations like <tt>gsub!</tt> the receiver itself becomes unsafe.</p>
|
1244
|
+
<div class="info"><p>The safety bit is lost always, no matter whether the transformation actually changed something.</p></div>
|
1245
|
+
<h5 id="conversion-and-coercion">5.1.4 Conversion and Coercion</h5>
|
1246
|
+
<p>Calling <tt>to_s</tt> on a safe string returns a safe string, but coercion with <tt>to_str</tt> returns an unsafe string.</p>
|
1247
|
+
<h5 id="copying">5.1.5 Copying</h5>
|
1248
|
+
<p>Calling <tt>dup</tt> or <tt>clone</tt> on safe strings yields safe strings.</p>
|
1249
|
+
<h4 id="squish">5.2 <tt>squish</tt></h4>
|
1250
|
+
<p>The method <tt>squish</tt> strips leading and trailing whitespace, and substitutes runs of whitespace with a single space each:</p>
|
1251
|
+
<div class="code_container">
|
1252
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1253
|
+
" \n foo\n\r \t bar \n".squish # => "foo bar"
|
1254
|
+
</pre>
|
1255
|
+
</div>
|
1256
|
+
<p>There’s also the destructive version <tt>String#squish!</tt>.</p>
|
1257
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/filters.rb</tt>.</p></div>
|
1258
|
+
<h4 id="truncate">5.3 <tt>truncate</tt></h4>
|
1259
|
+
<p>The method <tt>truncate</tt> returns a copy of its receiver truncated after a given <tt>length</tt>:</p>
|
1260
|
+
<div class="code_container">
|
1261
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1262
|
+
"Oh dear! Oh dear! I shall be late!".truncate(20)
|
1263
|
+
# => "Oh dear! Oh dear!..."
|
1264
|
+
</pre>
|
1265
|
+
</div>
|
1266
|
+
<p>Ellipsis can be customized with the <tt>:omission</tt> option:</p>
|
1267
|
+
<div class="code_container">
|
1268
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1269
|
+
"Oh dear! Oh dear! I shall be late!".truncate(20, :omission => '&hellip;')
|
1270
|
+
# => "Oh dear! Oh &hellip;"
|
1271
|
+
</pre>
|
1272
|
+
</div>
|
1273
|
+
<p>Note in particular that truncation takes into account the length of the omission string.</p>
|
1274
|
+
<p>Pass a <tt>:separator</tt> to truncate the string at a natural break:</p>
|
1275
|
+
<div class="code_container">
|
1276
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1277
|
+
"Oh dear! Oh dear! I shall be late!".truncate(18)
|
1278
|
+
# => "Oh dear! Oh dea..."
|
1279
|
+
"Oh dear! Oh dear! I shall be late!".truncate(18, :separator => ' ')
|
1280
|
+
# => "Oh dear! Oh..."
|
1281
|
+
</pre>
|
1282
|
+
</div>
|
1283
|
+
<p>In the above example “dear” gets cut first, but then <tt>:separator</tt> prevents it.</p>
|
1284
|
+
<div class="warning"><p>The option <tt>:separator</tt> can’t be a regexp.</p></div>
|
1285
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/filters.rb</tt>.</p></div>
|
1286
|
+
<h4 id="inquiry">5.4 <tt>inquiry</tt></h4>
|
1287
|
+
<p>The <tt>inquiry</tt> method converts a string into a <tt>StringInquirer</tt> object making equality checks prettier.</p>
|
1288
|
+
<div class="code_container">
|
1289
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1290
|
+
"production".inquiry.production? # => true
|
1291
|
+
"active".inquiry.inactive? # => false
|
1292
|
+
</pre>
|
1293
|
+
</div>
|
1294
|
+
<h4 id="key-based-interpolation">5.5 Key-based Interpolation</h4>
|
1295
|
+
<p>In Ruby 1.9 the <tt>%</tt> string operator supports key-based interpolation, both formatted and unformatted:</p>
|
1296
|
+
<div class="code_container">
|
1297
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1298
|
+
"Total is %<total>.02f" % {:total => 43.1} # => Total is 43.10
|
1299
|
+
"I say %{foo}" % {:foo => "wadus"} # => "I say wadus"
|
1300
|
+
"I say %{woo}" % {:foo => "wadus"} # => KeyError
|
1301
|
+
</pre>
|
1302
|
+
</div>
|
1303
|
+
<p>Active Support adds that functionality to <tt>%</tt> in previous versions of Ruby.</p>
|
1304
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/interpolation.rb</tt>.</p></div>
|
1305
|
+
<h4 id="starts_with-and-ends_with">5.6 <tt>starts_with?</tt> and <tt>ends_with?</tt></h4>
|
1306
|
+
<p>Active Support defines 3rd person aliases of <tt>String#start_with?</tt> and <tt>String#end_with?</tt>:</p>
|
1307
|
+
<div class="code_container">
|
1308
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1309
|
+
"foo".starts_with?("f") # => true
|
1310
|
+
"foo".ends_with?("o") # => true
|
1311
|
+
</pre>
|
1312
|
+
</div>
|
1313
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/starts_ends_with.rb</tt>.</p></div>
|
1314
|
+
<h4 id="strip_heredoc">5.7 <tt>strip_heredoc</tt></h4>
|
1315
|
+
<p>The method <tt>strip_heredoc</tt> strips indentation in heredocs.</p>
|
1316
|
+
<p>For example in</p>
|
1317
|
+
<div class="code_container">
|
1318
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1319
|
+
if options[:usage]
|
1320
|
+
puts <<-USAGE.strip_heredoc
|
1321
|
+
This command does such and such.
|
1322
|
+
|
1323
|
+
Supported options are:
|
1324
|
+
-h This message
|
1325
|
+
...
|
1326
|
+
USAGE
|
1327
|
+
end
|
1328
|
+
</pre>
|
1329
|
+
</div>
|
1330
|
+
<p>the user would see the usage message aligned against the left margin.</p>
|
1331
|
+
<p>Technically, it looks for the least indented line in the whole string, and removes
|
1332
|
+
that amount of leading whitespace.</p>
|
1333
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/strip.rb</tt>.</p></div>
|
1334
|
+
<h4 id="access">5.8 Access</h4>
|
1335
|
+
<h5 id="at-position">5.8.1 <tt>at(position)</tt></h5>
|
1336
|
+
<p>Returns the character of the string at position <tt>position</tt>:</p>
|
1337
|
+
<div class="code_container">
|
1338
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1339
|
+
"hello".at(0) # => "h"
|
1340
|
+
"hello".at(4) # => "o"
|
1341
|
+
"hello".at(-1) # => "o"
|
1342
|
+
"hello".at(10) # => ERROR if < 1.9, nil in 1.9
|
1343
|
+
</pre>
|
1344
|
+
</div>
|
1345
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/access.rb</tt>.</p></div>
|
1346
|
+
<h5 id="from-position">5.8.2 <tt>from(position)</tt></h5>
|
1347
|
+
<p>Returns the substring of the string starting at position <tt>position</tt>:</p>
|
1348
|
+
<div class="code_container">
|
1349
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1350
|
+
"hello".from(0) # => "hello"
|
1351
|
+
"hello".from(2) # => "llo"
|
1352
|
+
"hello".from(-2) # => "lo"
|
1353
|
+
"hello".from(10) # => "" if < 1.9, nil in 1.9
|
1354
|
+
</pre>
|
1355
|
+
</div>
|
1356
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/access.rb</tt>.</p></div>
|
1357
|
+
<h5 id="to-position">5.8.3 <tt>to(position)</tt></h5>
|
1358
|
+
<p>Returns the substring of the string up to position <tt>position</tt>:</p>
|
1359
|
+
<div class="code_container">
|
1360
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1361
|
+
"hello".to(0) # => "h"
|
1362
|
+
"hello".to(2) # => "hel"
|
1363
|
+
"hello".to(-2) # => "hell"
|
1364
|
+
"hello".to(10) # => "hello"
|
1365
|
+
</pre>
|
1366
|
+
</div>
|
1367
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/access.rb</tt>.</p></div>
|
1368
|
+
<h5 id="first-limit-1">5.8.4 <tt>first(limit = 1)</tt></h5>
|
1369
|
+
<p>The call <tt>str.first(n)</tt> is equivalent to <tt>str.to(n-1)</tt> if <tt>n</tt> > 0, and returns an empty string for <tt>n</tt> == 0.</p>
|
1370
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/access.rb</tt>.</p></div>
|
1371
|
+
<h5 id="last-limit-1">5.8.5 <tt>last(limit = 1)</tt></h5>
|
1372
|
+
<p>The call <tt>str.last(n)</tt> is equivalent to <tt>str.from(-n)</tt> if <tt>n</tt> > 0, and returns an empty string for <tt>n</tt> == 0.</p>
|
1373
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/access.rb</tt>.</p></div>
|
1374
|
+
<h4 id="inflections">5.9 Inflections</h4>
|
1375
|
+
<h5 id="pluralize">5.9.1 <tt>pluralize</tt></h5>
|
1376
|
+
<p>The method <tt>pluralize</tt> returns the plural of its receiver:</p>
|
1377
|
+
<div class="code_container">
|
1378
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1379
|
+
"table".pluralize # => "tables"
|
1380
|
+
"ruby".pluralize # => "rubies"
|
1381
|
+
"equipment".pluralize # => "equipment"
|
1382
|
+
</pre>
|
1383
|
+
</div>
|
1384
|
+
<p>As the previous example shows, Active Support knows some irregular plurals and uncountable nouns. Built-in rules can be extended in <tt>config/initializers/inflections.rb</tt>. That file is generated by the <tt>rails</tt> command and has instructions in comments.</p>
|
1385
|
+
<p><tt>pluralize</tt> can also take an optional <tt>count</tt> parameter. If <tt>count == 1</tt> the singular form will be returned. For any other value of <tt>count</tt> the plural form will be returned:</p>
|
1386
|
+
<div class="code_container">
|
1387
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1388
|
+
"dude".pluralize(0) # => "dudes"
|
1389
|
+
"dude".pluralize(1) # => "dude"
|
1390
|
+
"dude".pluralize(2) # => "dudes"
|
1391
|
+
</pre>
|
1392
|
+
</div>
|
1393
|
+
<p>Active Record uses this method to compute the default table name that corresponds to a model:</p>
|
1394
|
+
<div class="code_container">
|
1395
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1396
|
+
# active_record/base.rb
|
1397
|
+
def undecorated_table_name(class_name = base_class.name)
|
1398
|
+
table_name = class_name.to_s.demodulize.underscore
|
1399
|
+
table_name = table_name.pluralize if pluralize_table_names
|
1400
|
+
table_name
|
1401
|
+
end
|
1402
|
+
</pre>
|
1403
|
+
</div>
|
1404
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
|
1405
|
+
<h5 id="singularize">5.9.2 <tt>singularize</tt></h5>
|
1406
|
+
<p>The inverse of <tt>pluralize</tt>:</p>
|
1407
|
+
<div class="code_container">
|
1408
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1409
|
+
"tables".singularize # => "table"
|
1410
|
+
"rubies".singularize # => "ruby"
|
1411
|
+
"equipment".singularize # => "equipment"
|
1412
|
+
</pre>
|
1413
|
+
</div>
|
1414
|
+
<p>Associations compute the name of the corresponding default associated class using this method:</p>
|
1415
|
+
<div class="code_container">
|
1416
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1417
|
+
# active_record/reflection.rb
|
1418
|
+
def derive_class_name
|
1419
|
+
class_name = name.to_s.camelize
|
1420
|
+
class_name = class_name.singularize if collection?
|
1421
|
+
class_name
|
1422
|
+
end
|
1423
|
+
</pre>
|
1424
|
+
</div>
|
1425
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
|
1426
|
+
<h5 id="camelize">5.9.3 <tt>camelize</tt></h5>
|
1427
|
+
<p>The method <tt>camelize</tt> returns its receiver in camel case:</p>
|
1428
|
+
<div class="code_container">
|
1429
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1430
|
+
"product".camelize # => "Product"
|
1431
|
+
"admin_user".camelize # => "AdminUser"
|
1432
|
+
</pre>
|
1433
|
+
</div>
|
1434
|
+
<p>As a rule of thumb you can think of this method as the one that transforms paths into Ruby class or module names, where slashes separate namespaces:</p>
|
1435
|
+
<div class="code_container">
|
1436
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1437
|
+
"backoffice/session".camelize # => "Backoffice::Session"
|
1438
|
+
</pre>
|
1439
|
+
</div>
|
1440
|
+
<p>For example, Action Pack uses this method to load the class that provides a certain session store:</p>
|
1441
|
+
<div class="code_container">
|
1442
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1443
|
+
# action_controller/metal/session_management.rb
|
1444
|
+
def session_store=(store)
|
1445
|
+
if store == :active_record_store
|
1446
|
+
self.session_store = ActiveRecord::SessionStore
|
1447
|
+
else
|
1448
|
+
@@session_store = store.is_a?(Symbol) ?
|
1449
|
+
ActionDispatch::Session.const_get(store.to_s.camelize) :
|
1450
|
+
store
|
1451
|
+
end
|
1452
|
+
end
|
1453
|
+
</pre>
|
1454
|
+
</div>
|
1455
|
+
<p><tt>camelize</tt> accepts an optional argument, it can be <tt>:upper</tt> (default), or <tt>:lower</tt>. With the latter the first letter becomes lowercase:</p>
|
1456
|
+
<div class="code_container">
|
1457
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1458
|
+
"visual_effect".camelize(:lower) # => "visualEffect"
|
1459
|
+
</pre>
|
1460
|
+
</div>
|
1461
|
+
<p>That may be handy to compute method names in a language that follows that convention, for example JavaScript.</p>
|
1462
|
+
<div class="info"><p>As a rule of thumb you can think of <tt>camelize</tt> as the inverse of <tt>underscore</tt>, though there are cases where that does not hold: <tt>“SSLError”.underscore.camelize</tt> gives back <tt>“SslError”</tt>. To support cases such as this, Active Support allows you to specify acronyms in <tt>config/initializers/inflections.rb</tt>:</p></div>
|
1463
|
+
<div class="code_container">
|
1464
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1465
|
+
ActiveSupport::Inflector.inflections do |inflect|
|
1466
|
+
inflect.acronym 'SSL'
|
1467
|
+
end
|
1468
|
+
|
1469
|
+
"SSLError".underscore.camelize #=> "SSLError"
|
1470
|
+
</pre>
|
1471
|
+
</div>
|
1472
|
+
<p><tt>camelize</tt> is aliased to <tt>camelcase</tt>.</p>
|
1473
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
|
1474
|
+
<h5 id="underscore">5.9.4 <tt>underscore</tt></h5>
|
1475
|
+
<p>The method <tt>underscore</tt> goes the other way around, from camel case to paths:</p>
|
1476
|
+
<div class="code_container">
|
1477
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1478
|
+
"Product".underscore # => "product"
|
1479
|
+
"AdminUser".underscore # => "admin_user"
|
1480
|
+
</pre>
|
1481
|
+
</div>
|
1482
|
+
<p>Also converts “::” back to “/”:</p>
|
1483
|
+
<div class="code_container">
|
1484
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1485
|
+
"Backoffice::Session".underscore # => "backoffice/session"
|
1486
|
+
</pre>
|
1487
|
+
</div>
|
1488
|
+
<p>and understands strings that start with lowercase:</p>
|
1489
|
+
<div class="code_container">
|
1490
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1491
|
+
"visualEffect".underscore # => "visual_effect"
|
1492
|
+
</pre>
|
1493
|
+
</div>
|
1494
|
+
<p><tt>underscore</tt> accepts no argument though.</p>
|
1495
|
+
<p>Rails class and module autoloading uses <tt>underscore</tt> to infer the relative path without extension of a file that would define a given missing constant:</p>
|
1496
|
+
<div class="code_container">
|
1497
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1498
|
+
# active_support/dependencies.rb
|
1499
|
+
def load_missing_constant(from_mod, const_name)
|
1500
|
+
...
|
1501
|
+
qualified_name = qualified_name_for from_mod, const_name
|
1502
|
+
path_suffix = qualified_name.underscore
|
1503
|
+
...
|
1504
|
+
end
|
1505
|
+
</pre>
|
1506
|
+
</div>
|
1507
|
+
<div class="info"><p>As a rule of thumb you can think of <tt>underscore</tt> as the inverse of <tt>camelize</tt>, though there are cases where that does not hold. For example, <tt>“SSLError”.underscore.camelize</tt> gives back <tt>“SslError”</tt>.</p></div>
|
1508
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
|
1509
|
+
<h5 id="titleize">5.9.5 <tt>titleize</tt></h5>
|
1510
|
+
<p>The method <tt>titleize</tt> capitalizes the words in the receiver:</p>
|
1511
|
+
<div class="code_container">
|
1512
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1513
|
+
"alice in wonderland".titleize # => "Alice In Wonderland"
|
1514
|
+
"fermat's enigma".titleize # => "Fermat's Enigma"
|
1515
|
+
</pre>
|
1516
|
+
</div>
|
1517
|
+
<p><tt>titleize</tt> is aliased to <tt>titlecase</tt>.</p>
|
1518
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
|
1519
|
+
<h5 id="dasherize">5.9.6 <tt>dasherize</tt></h5>
|
1520
|
+
<p>The method <tt>dasherize</tt> replaces the underscores in the receiver with dashes:</p>
|
1521
|
+
<div class="code_container">
|
1522
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1523
|
+
"name".dasherize # => "name"
|
1524
|
+
"contact_data".dasherize # => "contact-data"
|
1525
|
+
</pre>
|
1526
|
+
</div>
|
1527
|
+
<p>The <span class="caps">XML</span> serializer of models uses this method to dasherize node names:</p>
|
1528
|
+
<div class="code_container">
|
1529
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1530
|
+
# active_model/serializers/xml.rb
|
1531
|
+
def reformat_name(name)
|
1532
|
+
name = name.camelize if camelize?
|
1533
|
+
dasherize? ? name.dasherize : name
|
1534
|
+
end
|
1535
|
+
</pre>
|
1536
|
+
</div>
|
1537
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
|
1538
|
+
<h5 id="demodulize">5.9.7 <tt>demodulize</tt></h5>
|
1539
|
+
<p>Given a string with a qualified constant name, <tt>demodulize</tt> returns the very constant name, that is, the rightmost part of it:</p>
|
1540
|
+
<div class="code_container">
|
1541
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1542
|
+
"Product".demodulize # => "Product"
|
1543
|
+
"Backoffice::UsersController".demodulize # => "UsersController"
|
1544
|
+
"Admin::Hotel::ReservationUtils".demodulize # => "ReservationUtils"
|
1545
|
+
</pre>
|
1546
|
+
</div>
|
1547
|
+
<p>Active Record for example uses this method to compute the name of a counter cache column:</p>
|
1548
|
+
<div class="code_container">
|
1549
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1550
|
+
# active_record/reflection.rb
|
1551
|
+
def counter_cache_column
|
1552
|
+
if options[:counter_cache] == true
|
1553
|
+
"#{active_record.name.demodulize.underscore.pluralize}_count"
|
1554
|
+
elsif options[:counter_cache]
|
1555
|
+
options[:counter_cache]
|
1556
|
+
end
|
1557
|
+
end
|
1558
|
+
</pre>
|
1559
|
+
</div>
|
1560
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
|
1561
|
+
<h5 id="deconstantize">5.9.8 <tt>deconstantize</tt></h5>
|
1562
|
+
<p>Given a string with a qualified constant reference expression, <tt>deconstantize</tt> removes the rightmost segment, generally leaving the name of the constant’s container:</p>
|
1563
|
+
<div class="code_container">
|
1564
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1565
|
+
"Product".deconstantize # => ""
|
1566
|
+
"Backoffice::UsersController".deconstantize # => "Backoffice"
|
1567
|
+
"Admin::Hotel::ReservationUtils".deconstantize # => "Admin::Hotel"
|
1568
|
+
</pre>
|
1569
|
+
</div>
|
1570
|
+
<p>Active Support for example uses this method in <tt>Module#qualified_const_set</tt>:</p>
|
1571
|
+
<div class="code_container">
|
1572
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1573
|
+
def qualified_const_set(path, value)
|
1574
|
+
QualifiedConstUtils.raise_if_absolute(path)
|
1575
|
+
|
1576
|
+
const_name = path.demodulize
|
1577
|
+
mod_name = path.deconstantize
|
1578
|
+
mod = mod_name.empty? ? self : qualified_const_get(mod_name)
|
1579
|
+
mod.const_set(const_name, value)
|
1580
|
+
end
|
1581
|
+
</pre>
|
1582
|
+
</div>
|
1583
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
|
1584
|
+
<h5 id="parameterize">5.9.9 <tt>parameterize</tt></h5>
|
1585
|
+
<p>The method <tt>parameterize</tt> normalizes its receiver in a way that can be used in pretty URLs.</p>
|
1586
|
+
<div class="code_container">
|
1587
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1588
|
+
"John Smith".parameterize # => "john-smith"
|
1589
|
+
"Kurt Gödel".parameterize # => "kurt-godel"
|
1590
|
+
</pre>
|
1591
|
+
</div>
|
1592
|
+
<p>In fact, the result string is wrapped in an instance of <tt>ActiveSupport::Multibyte::Chars</tt>.</p>
|
1593
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
|
1594
|
+
<h5 id="tableize">5.9.10 <tt>tableize</tt></h5>
|
1595
|
+
<p>The method <tt>tableize</tt> is <tt>underscore</tt> followed by <tt>pluralize</tt>.</p>
|
1596
|
+
<div class="code_container">
|
1597
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1598
|
+
"Person".tableize # => "people"
|
1599
|
+
"Invoice".tableize # => "invoices"
|
1600
|
+
"InvoiceLine".tableize # => "invoice_lines"
|
1601
|
+
</pre>
|
1602
|
+
</div>
|
1603
|
+
<p>As a rule of thumb, <tt>tableize</tt> returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight <tt>tableize</tt> indeed, because it also demodulizes the class name and checks a few options that may affect the returned string.</p>
|
1604
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
|
1605
|
+
<h5 id="classify">5.9.11 <tt>classify</tt></h5>
|
1606
|
+
<p>The method <tt>classify</tt> is the inverse of <tt>tableize</tt>. It gives you the class name corresponding to a table name:</p>
|
1607
|
+
<div class="code_container">
|
1608
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1609
|
+
"people".classify # => "Person"
|
1610
|
+
"invoices".classify # => "Invoice"
|
1611
|
+
"invoice_lines".classify # => "InvoiceLine"
|
1612
|
+
</pre>
|
1613
|
+
</div>
|
1614
|
+
<p>The method understands qualified table names:</p>
|
1615
|
+
<div class="code_container">
|
1616
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1617
|
+
"highrise_production.companies".classify # => "Company"
|
1618
|
+
</pre>
|
1619
|
+
</div>
|
1620
|
+
<p>Note that <tt>classify</tt> returns a class name as a string. You can get the actual class object invoking <tt>constantize</tt> on it, explained next.</p>
|
1621
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
|
1622
|
+
<h5 id="constantize">5.9.12 <tt>constantize</tt></h5>
|
1623
|
+
<p>The method <tt>constantize</tt> resolves the constant reference expression in its receiver:</p>
|
1624
|
+
<div class="code_container">
|
1625
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1626
|
+
"Fixnum".constantize # => Fixnum
|
1627
|
+
|
1628
|
+
module M
|
1629
|
+
X = 1
|
1630
|
+
end
|
1631
|
+
"M::X".constantize # => 1
|
1632
|
+
</pre>
|
1633
|
+
</div>
|
1634
|
+
<p>If the string evaluates to no known constant, or its content is not even a valid constant name, <tt>constantize</tt> raises <tt>NameError</tt>.</p>
|
1635
|
+
<p>Constant name resolution by <tt>constantize</tt> starts always at the top-level <tt>Object</tt> even if there is no leading “::”.</p>
|
1636
|
+
<div class="code_container">
|
1637
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1638
|
+
X = :in_Object
|
1639
|
+
module M
|
1640
|
+
X = :in_M
|
1641
|
+
|
1642
|
+
X # => :in_M
|
1643
|
+
"::X".constantize # => :in_Object
|
1644
|
+
"X".constantize # => :in_Object (!)
|
1645
|
+
end
|
1646
|
+
</pre>
|
1647
|
+
</div>
|
1648
|
+
<p>So, it is in general not equivalent to what Ruby would do in the same spot, had a real constant be evaluated.</p>
|
1649
|
+
<p>Mailer test cases obtain the mailer being tested from the name of the test class using <tt>constantize</tt>:</p>
|
1650
|
+
<div class="code_container">
|
1651
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1652
|
+
# action_mailer/test_case.rb
|
1653
|
+
def determine_default_mailer(name)
|
1654
|
+
name.sub(/Test$/, '').constantize
|
1655
|
+
rescue NameError => e
|
1656
|
+
raise NonInferrableMailerError.new(name)
|
1657
|
+
end
|
1658
|
+
</pre>
|
1659
|
+
</div>
|
1660
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
|
1661
|
+
<h5 id="humanize">5.9.13 <tt>humanize</tt></h5>
|
1662
|
+
<p>The method <tt>humanize</tt> gives you a sensible name for display out of an attribute name. To do so it replaces underscores with spaces, removes any “_id” suffix, and capitalizes the first word:</p>
|
1663
|
+
<div class="code_container">
|
1664
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1665
|
+
"name".humanize # => "Name"
|
1666
|
+
"author_id".humanize # => "Author"
|
1667
|
+
"comments_count".humanize # => "Comments count"
|
1668
|
+
</pre>
|
1669
|
+
</div>
|
1670
|
+
<p>The helper method <tt>full_messages</tt> uses <tt>humanize</tt> as a fallback to include attribute names:</p>
|
1671
|
+
<div class="code_container">
|
1672
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1673
|
+
def full_messages
|
1674
|
+
full_messages = []
|
1675
|
+
|
1676
|
+
each do |attribute, messages|
|
1677
|
+
...
|
1678
|
+
attr_name = attribute.to_s.gsub('.', '_').humanize
|
1679
|
+
attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
|
1680
|
+
...
|
1681
|
+
end
|
1682
|
+
|
1683
|
+
full_messages
|
1684
|
+
end
|
1685
|
+
</pre>
|
1686
|
+
</div>
|
1687
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
|
1688
|
+
<h5 id="foreign_key">5.9.14 <tt>foreign_key</tt></h5>
|
1689
|
+
<p>The method <tt>foreign_key</tt> gives a foreign key column name from a class name. To do so it demodulizes, underscores, and adds “_id”:</p>
|
1690
|
+
<div class="code_container">
|
1691
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1692
|
+
"User".foreign_key # => "user_id"
|
1693
|
+
"InvoiceLine".foreign_key # => "invoice_line_id"
|
1694
|
+
"Admin::Session".foreign_key # => "session_id"
|
1695
|
+
</pre>
|
1696
|
+
</div>
|
1697
|
+
<p>Pass a false argument if you do not want the underscore in “_id”:</p>
|
1698
|
+
<div class="code_container">
|
1699
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1700
|
+
"User".foreign_key(false) # => "userid"
|
1701
|
+
</pre>
|
1702
|
+
</div>
|
1703
|
+
<p>Associations use this method to infer foreign keys, for example <tt>has_one</tt> and <tt>has_many</tt> do this:</p>
|
1704
|
+
<div class="code_container">
|
1705
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1706
|
+
# active_record/associations.rb
|
1707
|
+
foreign_key = options[:foreign_key] || reflection.active_record.name.foreign_key
|
1708
|
+
</pre>
|
1709
|
+
</div>
|
1710
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
|
1711
|
+
<h4 id="string-conversions">5.10 Conversions</h4>
|
1712
|
+
<h5 id="ord">5.10.1 <tt>ord</tt></h5>
|
1713
|
+
<p>Ruby 1.9 defines <tt>ord</tt> to be the codepoint of the first character of the receiver. Active Support backports <tt>ord</tt> for single-byte encodings like <span class="caps">ASCII</span> or <span class="caps">ISO</span>-8859-1 in Ruby 1.8:</p>
|
1714
|
+
<div class="code_container">
|
1715
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1716
|
+
"a".ord # => 97
|
1717
|
+
"à".ord # => 224, in ISO-8859-1
|
1718
|
+
</pre>
|
1719
|
+
</div>
|
1720
|
+
<p>In Ruby 1.8 <tt>ord</tt> doesn’t work in general in UTF8 strings, use the multibyte support in Active Support for that:</p>
|
1721
|
+
<div class="code_container">
|
1722
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1723
|
+
"a".mb_chars.ord # => 97
|
1724
|
+
"à".mb_chars.ord # => 224, in UTF8
|
1725
|
+
</pre>
|
1726
|
+
</div>
|
1727
|
+
<p>Note that the 224 is different in both examples. In <span class="caps">ISO</span>-8859-1 “à” is represented as a single byte, 224. Its single-character representation in UTF8 has two bytes, namely 195 and 160, but its Unicode codepoint is 224. If we call <tt>ord</tt> on the UTF8 string “à” the return value will be 195 in Ruby 1.8. That is not an error, because UTF8 is unsupported, the call itself would be bogus.</p>
|
1728
|
+
<div class="info"><p><tt>ord</tt> is equivalent to <tt>getbyte(0)</tt>.</p></div>
|
1729
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/conversions.rb</tt>.</p></div>
|
1730
|
+
<h5 id="getbyte">5.10.2 <tt>getbyte</tt></h5>
|
1731
|
+
<p>Active Support backports <tt>getbyte</tt> from Ruby 1.9:</p>
|
1732
|
+
<div class="code_container">
|
1733
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1734
|
+
"foo".getbyte(0) # => 102, same as "foo".ord
|
1735
|
+
"foo".getbyte(1) # => 111
|
1736
|
+
"foo".getbyte(9) # => nil
|
1737
|
+
"foo".getbyte(-1) # => 111
|
1738
|
+
</pre>
|
1739
|
+
</div>
|
1740
|
+
<div class="info"><p><tt>getbyte</tt> is equivalent to <tt>[]</tt>.</p></div>
|
1741
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/conversions.rb</tt>.</p></div>
|
1742
|
+
<h5 id="to_date-to_time-to_datetime">5.10.3 <tt>to_date</tt>, <tt>to_time</tt>, <tt>to_datetime</tt></h5>
|
1743
|
+
<p>The methods <tt>to_date</tt>, <tt>to_time</tt>, and <tt>to_datetime</tt> are basically convenience wrappers around <tt>Date._parse</tt>:</p>
|
1744
|
+
<div class="code_container">
|
1745
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1746
|
+
"2010-07-27".to_date # => Tue, 27 Jul 2010
|
1747
|
+
"2010-07-27 23:37:00".to_time # => Tue Jul 27 23:37:00 UTC 2010
|
1748
|
+
"2010-07-27 23:37:00".to_datetime # => Tue, 27 Jul 2010 23:37:00 +0000
|
1749
|
+
</pre>
|
1750
|
+
</div>
|
1751
|
+
<p><tt>to_time</tt> receives an optional argument <tt>:utc</tt> or <tt>:local</tt>, to indicate which time zone you want the time in:</p>
|
1752
|
+
<div class="code_container">
|
1753
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1754
|
+
"2010-07-27 23:42:00".to_time(:utc) # => Tue Jul 27 23:42:00 UTC 2010
|
1755
|
+
"2010-07-27 23:42:00".to_time(:local) # => Tue Jul 27 23:42:00 +0200 2010
|
1756
|
+
</pre>
|
1757
|
+
</div>
|
1758
|
+
<p>Default is <tt>:utc</tt>.</p>
|
1759
|
+
<p>Please refer to the documentation of <tt>Date._parse</tt> for further details.</p>
|
1760
|
+
<div class="info"><p>The three of them return <tt>nil</tt> for blank receivers.</p></div>
|
1761
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/string/conversions.rb</tt>.</p></div>
|
1762
|
+
<h3 id="extensions-to-numeric">6 Extensions to <tt>Numeric</tt></h3>
|
1763
|
+
<h4 id="bytes">6.1 Bytes</h4>
|
1764
|
+
<p>All numbers respond to these methods:</p>
|
1765
|
+
<div class="code_container">
|
1766
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1767
|
+
bytes
|
1768
|
+
kilobytes
|
1769
|
+
megabytes
|
1770
|
+
gigabytes
|
1771
|
+
terabytes
|
1772
|
+
petabytes
|
1773
|
+
exabytes
|
1774
|
+
</pre>
|
1775
|
+
</div>
|
1776
|
+
<p>They return the corresponding amount of bytes, using a conversion factor of 1024:</p>
|
1777
|
+
<div class="code_container">
|
1778
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1779
|
+
2.kilobytes # => 2048
|
1780
|
+
3.megabytes # => 3145728
|
1781
|
+
3.5.gigabytes # => 3758096384
|
1782
|
+
-4.exabytes # => -4611686018427387904
|
1783
|
+
</pre>
|
1784
|
+
</div>
|
1785
|
+
<p>Singular forms are aliased so you are able to say:</p>
|
1786
|
+
<div class="code_container">
|
1787
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1788
|
+
1.megabyte # => 1048576
|
1789
|
+
</pre>
|
1790
|
+
</div>
|
1791
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/numeric/bytes.rb</tt>.</p></div>
|
1792
|
+
<h3 id="extensions-to-integer">7 Extensions to <tt>Integer</tt></h3>
|
1793
|
+
<h4 id="multiple_of">7.1 <tt>multiple_of?</tt></h4>
|
1794
|
+
<p>The method <tt>multiple_of?</tt> tests whether an integer is multiple of the argument:</p>
|
1795
|
+
<div class="code_container">
|
1796
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1797
|
+
2.multiple_of?(1) # => true
|
1798
|
+
1.multiple_of?(2) # => false
|
1799
|
+
</pre>
|
1800
|
+
</div>
|
1801
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/integer/multiple.rb</tt>.</p></div>
|
1802
|
+
<h4 id="ordinalize">7.2 <tt>ordinalize</tt></h4>
|
1803
|
+
<p>The method <tt>ordinalize</tt> returns the ordinal string corresponding to the receiver integer:</p>
|
1804
|
+
<div class="code_container">
|
1805
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1806
|
+
1.ordinalize # => "1st"
|
1807
|
+
2.ordinalize # => "2nd"
|
1808
|
+
53.ordinalize # => "53rd"
|
1809
|
+
2009.ordinalize # => "2009th"
|
1810
|
+
-21.ordinalize # => "-21st"
|
1811
|
+
-134.ordinalize # => "-134th"
|
1812
|
+
</pre>
|
1813
|
+
</div>
|
1814
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/integer/inflections.rb</tt>.</p></div>
|
1815
|
+
<h3 id="extensions-to-float">8 Extensions to <tt>Float</tt></h3>
|
1816
|
+
<h4 id="round">8.1 <tt>round</tt></h4>
|
1817
|
+
<p>The built-in method <tt>Float#round</tt> rounds a float to the nearest integer. In Ruby 1.9 this method takes an optional argument to let you specify a precision. Active Support adds that functionality to <tt>round</tt> in previous versions of Ruby:</p>
|
1818
|
+
<div class="code_container">
|
1819
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1820
|
+
Math::E.round(4) # => 2.7183
|
1821
|
+
</pre>
|
1822
|
+
</div>
|
1823
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/float/rounding.rb</tt>.</p></div>
|
1824
|
+
<h3 id="extensions-to-bigdecimal">9 Extensions to <tt>BigDecimal</tt></h3>
|
1825
|
+
<p>…</p>
|
1826
|
+
<h3 id="extensions-to-enumerable">10 Extensions to <tt>Enumerable</tt></h3>
|
1827
|
+
<h4 id="group_by">10.1 <tt>group_by</tt></h4>
|
1828
|
+
<p>Active Support redefines <tt>group_by</tt> in Ruby 1.8.7 so that it returns an ordered hash as in 1.9:</p>
|
1829
|
+
<div class="code_container">
|
1830
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1831
|
+
entries_by_surname_initial = address_book.group_by do |entry|
|
1832
|
+
entry.surname.at(0).upcase
|
1833
|
+
end
|
1834
|
+
</pre>
|
1835
|
+
</div>
|
1836
|
+
<p>Distinct block return values are added to the hash as they come, so that’s the resulting order.</p>
|
1837
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/enumerable.rb</tt>.</p></div>
|
1838
|
+
<h4 id="sum">10.2 <tt>sum</tt></h4>
|
1839
|
+
<p>The method <tt>sum</tt> adds the elements of an enumerable:</p>
|
1840
|
+
<div class="code_container">
|
1841
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1842
|
+
[1, 2, 3].sum # => 6
|
1843
|
+
(1..100).sum # => 5050
|
1844
|
+
</pre>
|
1845
|
+
</div>
|
1846
|
+
<p>Addition only assumes the elements respond to <tt>+</tt>:</p>
|
1847
|
+
<div class="code_container">
|
1848
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1849
|
+
[[1, 2], [2, 3], [3, 4]].sum # => [1, 2, 2, 3, 3, 4]
|
1850
|
+
%w(foo bar baz).sum # => "foobarbaz"
|
1851
|
+
{:a => 1, :b => 2, :c => 3}.sum # => [:b, 2, :c, 3, :a, 1]
|
1852
|
+
</pre>
|
1853
|
+
</div>
|
1854
|
+
<p>The sum of an empty collection is zero by default, but this is customizable:</p>
|
1855
|
+
<div class="code_container">
|
1856
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1857
|
+
[].sum # => 0
|
1858
|
+
[].sum(1) # => 1
|
1859
|
+
</pre>
|
1860
|
+
</div>
|
1861
|
+
<p>If a block is given, <tt>sum</tt> becomes an iterator that yields the elements of the collection and sums the returned values:</p>
|
1862
|
+
<div class="code_container">
|
1863
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1864
|
+
(1..5).sum {|n| n * 2 } # => 30
|
1865
|
+
[2, 4, 6, 8, 10].sum # => 30
|
1866
|
+
</pre>
|
1867
|
+
</div>
|
1868
|
+
<p>The sum of an empty receiver can be customized in this form as well:</p>
|
1869
|
+
<div class="code_container">
|
1870
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1871
|
+
[].sum(1) {|n| n**3} # => 1
|
1872
|
+
</pre>
|
1873
|
+
</div>
|
1874
|
+
<p>The method <tt>ActiveRecord::Observer#observed_subclasses</tt> for example is implemented this way:</p>
|
1875
|
+
<div class="code_container">
|
1876
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1877
|
+
def observed_subclasses
|
1878
|
+
observed_classes.sum([]) { |klass| klass.send(:subclasses) }
|
1879
|
+
end
|
1880
|
+
</pre>
|
1881
|
+
</div>
|
1882
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/enumerable.rb</tt>.</p></div>
|
1883
|
+
<h4 id="each_with_object">10.3 <tt>each_with_object</tt></h4>
|
1884
|
+
<p>The <tt>inject</tt> method offers iteration with an accumulator:</p>
|
1885
|
+
<div class="code_container">
|
1886
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1887
|
+
[2, 3, 4].inject(1) {|product, i| product*i } # => 24
|
1888
|
+
</pre>
|
1889
|
+
</div>
|
1890
|
+
<p>The block is expected to return the value for the accumulator in the next iteration, and this makes building mutable objects a bit cumbersome:</p>
|
1891
|
+
<div class="code_container">
|
1892
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1893
|
+
[1, 2].inject({}) {|h, i| h[i] = i**2; h} # => {1 => 1, 2 => 4}
|
1894
|
+
</pre>
|
1895
|
+
</div>
|
1896
|
+
<p>See that spurious “<tt>; h</tt>”?</p>
|
1897
|
+
<p>Active Support backports <tt>each_with_object</tt> from Ruby 1.9, which addresses that use case. It iterates over the collection, passes the accumulator, and returns the accumulator when done. You normally modify the accumulator in place. The example above would be written this way:</p>
|
1898
|
+
<div class="code_container">
|
1899
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1900
|
+
[1, 2].each_with_object({}) {|i, h| h[i] = i**2} # => {1 => 1, 2 => 4}
|
1901
|
+
</pre>
|
1902
|
+
</div>
|
1903
|
+
<div class="warning"><p>Note that the item of the collection and the accumulator come in different order in <tt>inject</tt> and <tt>each_with_object</tt>.</p></div>
|
1904
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/enumerable.rb</tt>.</p></div>
|
1905
|
+
<h4 id="index_by">10.4 <tt>index_by</tt></h4>
|
1906
|
+
<p>The method <tt>index_by</tt> generates a hash with the elements of an enumerable indexed by some key.</p>
|
1907
|
+
<p>It iterates through the collection and passes each element to a block. The element will be keyed by the value returned by the block:</p>
|
1908
|
+
<div class="code_container">
|
1909
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1910
|
+
invoices.index_by(&:number)
|
1911
|
+
# => {'2009-032' => <Invoice ...>, '2009-008' => <Invoice ...>, ...}
|
1912
|
+
</pre>
|
1913
|
+
</div>
|
1914
|
+
<div class="warning"><p>Keys should normally be unique. If the block returns the same value for different elements no collection is built for that key. The last item will win.</p></div>
|
1915
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/enumerable.rb</tt>.</p></div>
|
1916
|
+
<h4 id="many">10.5 <tt>many?</tt></h4>
|
1917
|
+
<p>The method <tt>many?</tt> is shorthand for <tt>collection.size > 1</tt>:</p>
|
1918
|
+
<div class="code_container">
|
1919
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
1920
|
+
<% if pages.many? %>
|
1921
|
+
<%= pagination_links %>
|
1922
|
+
<% end %>
|
1923
|
+
</pre>
|
1924
|
+
</div>
|
1925
|
+
<p>If an optional block is given, <tt>many?</tt> only takes into account those elements that return true:</p>
|
1926
|
+
<div class="code_container">
|
1927
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1928
|
+
@see_more = videos.many? {|video| video.category == params[:category]}
|
1929
|
+
</pre>
|
1930
|
+
</div>
|
1931
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/enumerable.rb</tt>.</p></div>
|
1932
|
+
<h4 id="exclude">10.6 <tt>exclude?</tt></h4>
|
1933
|
+
<p>The predicate <tt>exclude?</tt> tests whether a given object does <strong>not</strong> belong to the collection. It is the negation of the built-in <tt>include?</tt>:</p>
|
1934
|
+
<div class="code_container">
|
1935
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1936
|
+
to_visit << node if visited.exclude?(node)
|
1937
|
+
</pre>
|
1938
|
+
</div>
|
1939
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/enumerable.rb</tt>.</p></div>
|
1940
|
+
<h3 id="extensions-to-array">11 Extensions to <tt>Array</tt></h3>
|
1941
|
+
<h4 id="accessing">11.1 Accessing</h4>
|
1942
|
+
<p>Active Support augments the <span class="caps">API</span> of arrays to ease certain ways of accessing them. For example, <tt>to</tt> returns the subarray of elements up to the one at the passed index:</p>
|
1943
|
+
<div class="code_container">
|
1944
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1945
|
+
%w(a b c d).to(2) # => %w(a b c)
|
1946
|
+
[].to(7) # => []
|
1947
|
+
</pre>
|
1948
|
+
</div>
|
1949
|
+
<p>Similarly, <tt>from</tt> returns the tail from the element at the passed index to the end. If the index is greater than the length of the array, it returns an empty array.</p>
|
1950
|
+
<div class="code_container">
|
1951
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1952
|
+
%w(a b c d).from(2) # => %w(c d)
|
1953
|
+
%w(a b c d).from(10) # => []
|
1954
|
+
[].from(0) # => []
|
1955
|
+
</pre>
|
1956
|
+
</div>
|
1957
|
+
<p>The methods <tt>second</tt>, <tt>third</tt>, <tt>fourth</tt>, and <tt>fifth</tt> return the corresponding element (<tt>first</tt> is built-in). Thanks to social wisdom and positive constructiveness all around, <tt>forty_two</tt> is also available.</p>
|
1958
|
+
<div class="code_container">
|
1959
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1960
|
+
%w(a b c d).third # => c
|
1961
|
+
%w(a b c d).fifth # => nil
|
1962
|
+
</pre>
|
1963
|
+
</div>
|
1964
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/array/access.rb</tt>.</p></div>
|
1965
|
+
<h4 id="random-access">11.2 Random Access</h4>
|
1966
|
+
<p>Active Support backports <tt>sample</tt> from Ruby 1.9:</p>
|
1967
|
+
<div class="code_container">
|
1968
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1969
|
+
shape_type = [Circle, Square, Triangle].sample
|
1970
|
+
# => Square, for example
|
1971
|
+
|
1972
|
+
shape_types = [Circle, Square, Triangle].sample(2)
|
1973
|
+
# => [Triangle, Circle], for example
|
1974
|
+
</pre>
|
1975
|
+
</div>
|
1976
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/array/random_access.rb</tt>.</p></div>
|
1977
|
+
<h4 id="adding-elements">11.3 Adding Elements</h4>
|
1978
|
+
<h5 id="prepend">11.3.1 <tt>prepend</tt></h5>
|
1979
|
+
<p>This method is an alias of <tt>Array#unshift</tt>.</p>
|
1980
|
+
<div class="code_container">
|
1981
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1982
|
+
%w(a b c d).prepend('e') # => %w(e a b c d)
|
1983
|
+
[].prepend(10) # => [10]
|
1984
|
+
</pre>
|
1985
|
+
</div>
|
1986
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/array/prepend_and_append.rb</tt>.</p></div>
|
1987
|
+
<h5 id="append">11.3.2 <tt>append</tt></h5>
|
1988
|
+
<p>This method is an alias of <tt>Array#<<</tt>.</p>
|
1989
|
+
<div class="code_container">
|
1990
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1991
|
+
%w(a b c d).append('e') # => %w(a b c d e)
|
1992
|
+
[].append([1,2]) # => [[1,2]]
|
1993
|
+
</pre>
|
1994
|
+
</div>
|
1995
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/array/prepend_and_append.rb</tt>.</p></div>
|
1996
|
+
<h4 id="options-extraction">11.4 Options Extraction</h4>
|
1997
|
+
<p>When the last argument in a method call is a hash, except perhaps for a <tt>&block</tt> argument, Ruby allows you to omit the brackets:</p>
|
1998
|
+
<div class="code_container">
|
1999
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2000
|
+
User.exists?(:email => params[:email])
|
2001
|
+
</pre>
|
2002
|
+
</div>
|
2003
|
+
<p>That syntactic sugar is used a lot in Rails to avoid positional arguments where there would be too many, offering instead interfaces that emulate named parameters. In particular it is very idiomatic to use a trailing hash for options.</p>
|
2004
|
+
<p>If a method expects a variable number of arguments and uses <tt>*</tt> in its declaration, however, such an options hash ends up being an item of the array of arguments, where it loses its role.</p>
|
2005
|
+
<p>In those cases, you may give an options hash a distinguished treatment with <tt>extract_options!</tt>. This method checks the type of the last item of an array. If it is a hash it pops it and returns it, otherwise it returns an empty hash.</p>
|
2006
|
+
<p>Let’s see for example the definition of the <tt>caches_action</tt> controller macro:</p>
|
2007
|
+
<div class="code_container">
|
2008
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2009
|
+
def caches_action(*actions)
|
2010
|
+
return unless cache_configured?
|
2011
|
+
options = actions.extract_options!
|
2012
|
+
...
|
2013
|
+
end
|
2014
|
+
</pre>
|
2015
|
+
</div>
|
2016
|
+
<p>This method receives an arbitrary number of action names, and an optional hash of options as last argument. With the call to <tt>extract_options!</tt> you obtain the options hash and remove it from <tt>actions</tt> in a simple and explicit way.</p>
|
2017
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/array/extract_options.rb</tt>.</p></div>
|
2018
|
+
<h4 id="array-conversions">11.5 Conversions</h4>
|
2019
|
+
<h5 id="to_sentence">11.5.1 <tt>to_sentence</tt></h5>
|
2020
|
+
<p>The method <tt>to_sentence</tt> turns an array into a string containing a sentence that enumerates its items:</p>
|
2021
|
+
<div class="code_container">
|
2022
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2023
|
+
%w().to_sentence # => ""
|
2024
|
+
%w(Earth).to_sentence # => "Earth"
|
2025
|
+
%w(Earth Wind).to_sentence # => "Earth and Wind"
|
2026
|
+
%w(Earth Wind Fire).to_sentence # => "Earth, Wind, and Fire"
|
2027
|
+
</pre>
|
2028
|
+
</div>
|
2029
|
+
<p>This method accepts three options:</p>
|
2030
|
+
<ul>
|
2031
|
+
<li><tt>:two_words_connector</tt>: What is used for arrays of length 2. Default is " and ".</li>
|
2032
|
+
<li><tt>:words_connector</tt>: What is used to join the elements of arrays with 3 or more elements, except for the last two. Default is ", ".</li>
|
2033
|
+
<li><tt>:last_word_connector</tt>: What is used to join the last items of an array with 3 or more elements. Default is ", and ".</li>
|
2034
|
+
</ul>
|
2035
|
+
<p>The defaults for these options can be localised, their keys are:</p>
|
2036
|
+
<table>
|
2037
|
+
<tr>
|
2038
|
+
<th>Option </th>
|
2039
|
+
<th>I18n key </th>
|
2040
|
+
</tr>
|
2041
|
+
<tr>
|
2042
|
+
<td> <tt>:two_words_connector</tt> </td>
|
2043
|
+
<td> <tt>support.array.two_words_connector</tt> </td>
|
2044
|
+
</tr>
|
2045
|
+
<tr>
|
2046
|
+
<td> <tt>:words_connector</tt> </td>
|
2047
|
+
<td> <tt>support.array.words_connector</tt> </td>
|
2048
|
+
</tr>
|
2049
|
+
<tr>
|
2050
|
+
<td> <tt>:last_word_connector</tt> </td>
|
2051
|
+
<td> <tt>support.array.last_word_connector</tt> </td>
|
2052
|
+
</tr>
|
2053
|
+
</table>
|
2054
|
+
<p>Options <tt>:connector</tt> and <tt>:skip_last_comma</tt> are deprecated.</p>
|
2055
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/array/conversions.rb</tt>.</p></div>
|
2056
|
+
<h5 id="to_formatted_s">11.5.2 <tt>to_formatted_s</tt></h5>
|
2057
|
+
<p>The method <tt>to_formatted_s</tt> acts like <tt>to_s</tt> by default.</p>
|
2058
|
+
<p>If the array contains items that respond to <tt>id</tt>, however, it may be passed the symbol <tt>:db</tt> as argument. That’s typically used with collections of ARs, though technically any object in Ruby 1.8 responds to <tt>id</tt> indeed. Returned strings are:</p>
|
2059
|
+
<div class="code_container">
|
2060
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2061
|
+
[].to_formatted_s(:db) # => "null"
|
2062
|
+
[user].to_formatted_s(:db) # => "8456"
|
2063
|
+
invoice.lines.to_formatted_s(:db) # => "23,567,556,12"
|
2064
|
+
</pre>
|
2065
|
+
</div>
|
2066
|
+
<p>Integers in the example above are supposed to come from the respective calls to <tt>id</tt>.</p>
|
2067
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/array/conversions.rb</tt>.</p></div>
|
2068
|
+
<h5 id="to_xml">11.5.3 <tt>to_xml</tt></h5>
|
2069
|
+
<p>The method <tt>to_xml</tt> returns a string containing an <span class="caps">XML</span> representation of its receiver:</p>
|
2070
|
+
<div class="code_container">
|
2071
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2072
|
+
Contributor.limit(2).order(:rank).to_xml
|
2073
|
+
# =>
|
2074
|
+
# <?xml version="1.0" encoding="UTF-8"?>
|
2075
|
+
# <contributors type="array">
|
2076
|
+
# <contributor>
|
2077
|
+
# <id type="integer">4356</id>
|
2078
|
+
# <name>Jeremy Kemper</name>
|
2079
|
+
# <rank type="integer">1</rank>
|
2080
|
+
# <url-id>jeremy-kemper</url-id>
|
2081
|
+
# </contributor>
|
2082
|
+
# <contributor>
|
2083
|
+
# <id type="integer">4404</id>
|
2084
|
+
# <name>David Heinemeier Hansson</name>
|
2085
|
+
# <rank type="integer">2</rank>
|
2086
|
+
# <url-id>david-heinemeier-hansson</url-id>
|
2087
|
+
# </contributor>
|
2088
|
+
# </contributors>
|
2089
|
+
</pre>
|
2090
|
+
</div>
|
2091
|
+
<p>To do so it sends <tt>to_xml</tt> to every item in turn, and collects the results under a root node. All items must respond to <tt>to_xml</tt>, an exception is raised otherwise.</p>
|
2092
|
+
<p>By default, the name of the root element is the underscorized and dasherized plural of the name of the class of the first item, provided the rest of elements belong to that type (checked with <tt>is_a?</tt>) and they are not hashes. In the example above that’s “contributors”.</p>
|
2093
|
+
<p>If there’s any element that does not belong to the type of the first one the root node becomes “records”:</p>
|
2094
|
+
<div class="code_container">
|
2095
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2096
|
+
[Contributor.first, Commit.first].to_xml
|
2097
|
+
# =>
|
2098
|
+
# <?xml version="1.0" encoding="UTF-8"?>
|
2099
|
+
# <records type="array">
|
2100
|
+
# <record>
|
2101
|
+
# <id type="integer">4583</id>
|
2102
|
+
# <name>Aaron Batalion</name>
|
2103
|
+
# <rank type="integer">53</rank>
|
2104
|
+
# <url-id>aaron-batalion</url-id>
|
2105
|
+
# </record>
|
2106
|
+
# <record>
|
2107
|
+
# <author>Joshua Peek</author>
|
2108
|
+
# <authored-timestamp type="datetime">2009-09-02T16:44:36Z</authored-timestamp>
|
2109
|
+
# <branch>origin/master</branch>
|
2110
|
+
# <committed-timestamp type="datetime">2009-09-02T16:44:36Z</committed-timestamp>
|
2111
|
+
# <committer>Joshua Peek</committer>
|
2112
|
+
# <git-show nil="true"></git-show>
|
2113
|
+
# <id type="integer">190316</id>
|
2114
|
+
# <imported-from-svn type="boolean">false</imported-from-svn>
|
2115
|
+
# <message>Kill AMo observing wrap_with_notifications since ARes was only using it</message>
|
2116
|
+
# <sha1>723a47bfb3708f968821bc969a9a3fc873a3ed58</sha1>
|
2117
|
+
# </record>
|
2118
|
+
# </records>
|
2119
|
+
</pre>
|
2120
|
+
</div>
|
2121
|
+
<p>If the receiver is an array of hashes the root element is by default also “records”:</p>
|
2122
|
+
<div class="code_container">
|
2123
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2124
|
+
[{:a => 1, :b => 2}, {:c => 3}].to_xml
|
2125
|
+
# =>
|
2126
|
+
# <?xml version="1.0" encoding="UTF-8"?>
|
2127
|
+
# <records type="array">
|
2128
|
+
# <record>
|
2129
|
+
# <b type="integer">2</b>
|
2130
|
+
# <a type="integer">1</a>
|
2131
|
+
# </record>
|
2132
|
+
# <record>
|
2133
|
+
# <c type="integer">3</c>
|
2134
|
+
# </record>
|
2135
|
+
# </records>
|
2136
|
+
</pre>
|
2137
|
+
</div>
|
2138
|
+
<div class="warning"><p>If the collection is empty the root element is by default “nil-classes”. That’s a gotcha, for example the root element of the list of contributors above would not be “contributors” if the collection was empty, but “nil-classes”. You may use the <tt>:root</tt> option to ensure a consistent root element.</p></div>
|
2139
|
+
<p>The name of children nodes is by default the name of the root node singularized. In the examples above we’ve seen “contributor” and “record”. The option <tt>:children</tt> allows you to set these node names.</p>
|
2140
|
+
<p>The default <span class="caps">XML</span> builder is a fresh instance of <tt>Builder::XmlMarkup</tt>. You can configure your own builder via the <tt>:builder</tt> option. The method also accepts options like <tt>:dasherize</tt> and friends, they are forwarded to the builder:</p>
|
2141
|
+
<div class="code_container">
|
2142
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2143
|
+
Contributor.limit(2).order(:rank).to_xml(:skip_types => true)
|
2144
|
+
# =>
|
2145
|
+
# <?xml version="1.0" encoding="UTF-8"?>
|
2146
|
+
# <contributors>
|
2147
|
+
# <contributor>
|
2148
|
+
# <id>4356</id>
|
2149
|
+
# <name>Jeremy Kemper</name>
|
2150
|
+
# <rank>1</rank>
|
2151
|
+
# <url-id>jeremy-kemper</url-id>
|
2152
|
+
# </contributor>
|
2153
|
+
# <contributor>
|
2154
|
+
# <id>4404</id>
|
2155
|
+
# <name>David Heinemeier Hansson</name>
|
2156
|
+
# <rank>2</rank>
|
2157
|
+
# <url-id>david-heinemeier-hansson</url-id>
|
2158
|
+
# </contributor>
|
2159
|
+
# </contributors>
|
2160
|
+
</pre>
|
2161
|
+
</div>
|
2162
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/array/conversions.rb</tt>.</p></div>
|
2163
|
+
<h4 id="wrapping">11.6 Wrapping</h4>
|
2164
|
+
<p>The method <tt>Array.wrap</tt> wraps its argument in an array unless it is already an array (or array-like).</p>
|
2165
|
+
<p>Specifically:</p>
|
2166
|
+
<ul>
|
2167
|
+
<li>If the argument is <tt>nil</tt> an empty list is returned.</li>
|
2168
|
+
<li>Otherwise, if the argument responds to <tt>to_ary</tt> it is invoked, and if the value of <tt>to_ary</tt> is not <tt>nil</tt>, it is returned.</li>
|
2169
|
+
<li>Otherwise, an array with the argument as its single element is returned.</li>
|
2170
|
+
</ul>
|
2171
|
+
<div class="code_container">
|
2172
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2173
|
+
Array.wrap(nil) # => []
|
2174
|
+
Array.wrap([1, 2, 3]) # => [1, 2, 3]
|
2175
|
+
Array.wrap(0) # => [0]
|
2176
|
+
</pre>
|
2177
|
+
</div>
|
2178
|
+
<p>This method is similar in purpose to <tt>Kernel#Array</tt>, but there are some differences:</p>
|
2179
|
+
<ul>
|
2180
|
+
<li>If the argument responds to <tt>to_ary</tt> the method is invoked. <tt>Kernel#Array</tt> moves on to try <tt>to_a</tt> if the returned value is <tt>nil</tt>, but <tt>Array.wrap</tt> returns <tt>nil</tt> right away.</li>
|
2181
|
+
<li>If the returned value from <tt>to_ary</tt> is neither <tt>nil</tt> nor an <tt>Array</tt> object, <tt>Kernel#Array</tt> raises an exception, while <tt>Array.wrap</tt> does not, it just returns the value.</li>
|
2182
|
+
<li>It does not call <tt>to_a</tt> on the argument, though special-cases <tt>nil</tt> to return an empty array.</li>
|
2183
|
+
</ul>
|
2184
|
+
<p>The last point is particularly worth comparing for some enumerables:</p>
|
2185
|
+
<div class="code_container">
|
2186
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2187
|
+
Array.wrap(:foo => :bar) # => [{:foo => :bar}]
|
2188
|
+
Array(:foo => :bar) # => [[:foo, :bar]]
|
2189
|
+
|
2190
|
+
Array.wrap("foo\nbar") # => ["foo\nbar"]
|
2191
|
+
Array("foo\nbar") # => ["foo\n", "bar"], in Ruby 1.8
|
2192
|
+
</pre>
|
2193
|
+
</div>
|
2194
|
+
<p>There’s also a related idiom that uses the splat operator:</p>
|
2195
|
+
<div class="code_container">
|
2196
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2197
|
+
[*object]
|
2198
|
+
</pre>
|
2199
|
+
</div>
|
2200
|
+
<p>which in Ruby 1.8 returns <tt>[nil]</tt> for <tt>nil</tt>, and calls to <tt>Array(object)</tt> otherwise. (Please if you know the exact behavior in 1.9 contact fxn.)</p>
|
2201
|
+
<p>Thus, in this case the behavior is different for <tt>nil</tt>, and the differences with <tt>Kernel#Array</tt> explained above apply to the rest of <tt>object</tt>s.</p>
|
2202
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/array/wrap.rb</tt>.</p></div>
|
2203
|
+
<h4 id="grouping">11.7 Grouping</h4>
|
2204
|
+
<h5 id="in_groups_of-number-fill_with-nil">11.7.1 <tt>in_groups_of(number, fill_with = nil)</tt></h5>
|
2205
|
+
<p>The method <tt>in_groups_of</tt> splits an array into consecutive groups of a certain size. It returns an array with the groups:</p>
|
2206
|
+
<div class="code_container">
|
2207
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2208
|
+
[1, 2, 3].in_groups_of(2) # => [[1, 2], [3, nil]]
|
2209
|
+
</pre>
|
2210
|
+
</div>
|
2211
|
+
<p>or yields them in turn if a block is passed:</p>
|
2212
|
+
<div class="code_container">
|
2213
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2214
|
+
<% sample.in_groups_of(3) do |a, b, c| %>
|
2215
|
+
<tr>
|
2216
|
+
<td><%=h a %></td>
|
2217
|
+
<td><%=h b %></td>
|
2218
|
+
<td><%=h c %></td>
|
2219
|
+
</tr>
|
2220
|
+
<% end %>
|
2221
|
+
</pre>
|
2222
|
+
</div>
|
2223
|
+
<p>The first example shows <tt>in_groups_of</tt> fills the last group with as many <tt>nil</tt> elements as needed to have the requested size. You can change this padding value using the second optional argument:</p>
|
2224
|
+
<div class="code_container">
|
2225
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2226
|
+
[1, 2, 3].in_groups_of(2, 0) # => [[1, 2], [3, 0]]
|
2227
|
+
</pre>
|
2228
|
+
</div>
|
2229
|
+
<p>And you can tell the method not to fill the last group passing <tt>false</tt>:</p>
|
2230
|
+
<div class="code_container">
|
2231
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2232
|
+
[1, 2, 3].in_groups_of(2, false) # => [[1, 2], [3]]
|
2233
|
+
</pre>
|
2234
|
+
</div>
|
2235
|
+
<p>As a consequence <tt>false</tt> can’t be a used as a padding value.</p>
|
2236
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/array/grouping.rb</tt>.</p></div>
|
2237
|
+
<h5 id="in_groups-number-fill_with-nil">11.7.2 <tt>in_groups(number, fill_with = nil)</tt></h5>
|
2238
|
+
<p>The method <tt>in_groups</tt> splits an array into a certain number of groups. The method returns an array with the groups:</p>
|
2239
|
+
<div class="code_container">
|
2240
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2241
|
+
%w(1 2 3 4 5 6 7).in_groups(3)
|
2242
|
+
# => [["1", "2", "3"], ["4", "5", nil], ["6", "7", nil]]
|
2243
|
+
</pre>
|
2244
|
+
</div>
|
2245
|
+
<p>or yields them in turn if a block is passed:</p>
|
2246
|
+
<div class="code_container">
|
2247
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2248
|
+
%w(1 2 3 4 5 6 7).in_groups(3) {|group| p group}
|
2249
|
+
["1", "2", "3"]
|
2250
|
+
["4", "5", nil]
|
2251
|
+
["6", "7", nil]
|
2252
|
+
</pre>
|
2253
|
+
</div>
|
2254
|
+
<p>The examples above show that <tt>in_groups</tt> fills some groups with a trailing <tt>nil</tt> element as needed. A group can get at most one of these extra elements, the rightmost one if any. And the groups that have them are always the last ones.</p>
|
2255
|
+
<p>You can change this padding value using the second optional argument:</p>
|
2256
|
+
<div class="code_container">
|
2257
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2258
|
+
%w(1 2 3 4 5 6 7).in_groups(3, "0")
|
2259
|
+
# => [["1", "2", "3"], ["4", "5", "0"], ["6", "7", "0"]]
|
2260
|
+
</pre>
|
2261
|
+
</div>
|
2262
|
+
<p>And you can tell the method not to fill the smaller groups passing <tt>false</tt>:</p>
|
2263
|
+
<div class="code_container">
|
2264
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2265
|
+
%w(1 2 3 4 5 6 7).in_groups(3, false)
|
2266
|
+
# => [["1", "2", "3"], ["4", "5"], ["6", "7"]]
|
2267
|
+
</pre>
|
2268
|
+
</div>
|
2269
|
+
<p>As a consequence <tt>false</tt> can’t be a used as a padding value.</p>
|
2270
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/array/grouping.rb</tt>.</p></div>
|
2271
|
+
<h5 id="split-value-nil">11.7.3 <tt>split(value = nil)</tt></h5>
|
2272
|
+
<p>The method <tt>split</tt> divides an array by a separator and returns the resulting chunks.</p>
|
2273
|
+
<p>If a block is passed the separators are those elements of the array for which the block returns true:</p>
|
2274
|
+
<div class="code_container">
|
2275
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2276
|
+
(-5..5).to_a.split { |i| i.multiple_of?(4) }
|
2277
|
+
# => [[-5], [-3, -2, -1], [1, 2, 3], [5]]
|
2278
|
+
</pre>
|
2279
|
+
</div>
|
2280
|
+
<p>Otherwise, the value received as argument, which defaults to <tt>nil</tt>, is the separator:</p>
|
2281
|
+
<div class="code_container">
|
2282
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2283
|
+
[0, 1, -5, 1, 1, "foo", "bar"].split(1)
|
2284
|
+
# => [[0], [-5], [], ["foo", "bar"]]
|
2285
|
+
</pre>
|
2286
|
+
</div>
|
2287
|
+
<div class="info"><p>Observe in the previous example that consecutive separators result in empty arrays.</p></div>
|
2288
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/array/grouping.rb</tt>.</p></div>
|
2289
|
+
<h3 id="extensions-to-hash">12 Extensions to <tt>Hash</tt></h3>
|
2290
|
+
<h4 id="hash-conversions">12.1 Conversions</h4>
|
2291
|
+
<h5 id="hash-to-xml">12.1.1 <tt>to_xml</tt></h5>
|
2292
|
+
<p>The method <tt>to_xml</tt> returns a string containing an <span class="caps">XML</span> representation of its receiver:</p>
|
2293
|
+
<div class="code_container">
|
2294
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2295
|
+
{"foo" => 1, "bar" => 2}.to_xml
|
2296
|
+
# =>
|
2297
|
+
# <?xml version="1.0" encoding="UTF-8"?>
|
2298
|
+
# <hash>
|
2299
|
+
# <foo type="integer">1</foo>
|
2300
|
+
# <bar type="integer">2</bar>
|
2301
|
+
# </hash>
|
2302
|
+
</pre>
|
2303
|
+
</div>
|
2304
|
+
<p>To do so, the method loops over the pairs and builds nodes that depend on the <em>values</em>. Given a pair <tt>key</tt>, <tt>value</tt>:</p>
|
2305
|
+
<ul>
|
2306
|
+
<li>If <tt>value</tt> is a hash there’s a recursive call with <tt>key</tt> as <tt>:root</tt>.</li>
|
2307
|
+
</ul>
|
2308
|
+
<ul>
|
2309
|
+
<li>If <tt>value</tt> is an array there’s a recursive call with <tt>key</tt> as <tt>:root</tt>, and <tt>key</tt> singularized as <tt>:children</tt>.</li>
|
2310
|
+
</ul>
|
2311
|
+
<ul>
|
2312
|
+
<li>If <tt>value</tt> is a callable object it must expect one or two arguments. Depending on the arity, the callable is invoked with the <tt>options</tt> hash as first argument with <tt>key</tt> as <tt>:root</tt>, and <tt>key</tt> singularized as second argument. Its return value becomes a new node.</li>
|
2313
|
+
</ul>
|
2314
|
+
<ul>
|
2315
|
+
<li>If <tt>value</tt> responds to <tt>to_xml</tt> the method is invoked with <tt>key</tt> as <tt>:root</tt>.</li>
|
2316
|
+
</ul>
|
2317
|
+
<ul>
|
2318
|
+
<li>Otherwise, a node with <tt>key</tt> as tag is created with a string representation of <tt>value</tt> as text node. If <tt>value</tt> is <tt>nil</tt> an attribute “nil” set to “true” is added. Unless the option <tt>:skip_types</tt> exists and is true, an attribute “type” is added as well according to the following mapping:
|
2319
|
+
<div class="code_container">
|
2320
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2321
|
+
XML_TYPE_NAMES = {
|
2322
|
+
"Symbol" => "symbol",
|
2323
|
+
"Fixnum" => "integer",
|
2324
|
+
"Bignum" => "integer",
|
2325
|
+
"BigDecimal" => "decimal",
|
2326
|
+
"Float" => "float",
|
2327
|
+
"TrueClass" => "boolean",
|
2328
|
+
"FalseClass" => "boolean",
|
2329
|
+
"Date" => "date",
|
2330
|
+
"DateTime" => "datetime",
|
2331
|
+
"Time" => "datetime"
|
2332
|
+
}
|
2333
|
+
</pre>
|
2334
|
+
</div>
|
2335
|
+
</li>
|
2336
|
+
</ul>
|
2337
|
+
<p>By default the root node is “hash”, but that’s configurable via the <tt>:root</tt> option.</p>
|
2338
|
+
<p>The default <span class="caps">XML</span> builder is a fresh instance of <tt>Builder::XmlMarkup</tt>. You can configure your own builder with the <tt>:builder</tt> option. The method also accepts options like <tt>:dasherize</tt> and friends, they are forwarded to the builder.</p>
|
2339
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/hash/conversions.rb</tt>.</p></div>
|
2340
|
+
<h4 id="merging">12.2 Merging</h4>
|
2341
|
+
<p>Ruby has a built-in method <tt>Hash#merge</tt> that merges two hashes:</p>
|
2342
|
+
<div class="code_container">
|
2343
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2344
|
+
{:a => 1, :b => 1}.merge(:a => 0, :c => 2)
|
2345
|
+
# => {:a => 0, :b => 1, :c => 2}
|
2346
|
+
</pre>
|
2347
|
+
</div>
|
2348
|
+
<p>Active Support defines a few more ways of merging hashes that may be convenient.</p>
|
2349
|
+
<h5 id="reverse_merge-and-reverse_merge">12.2.1 <tt>reverse_merge</tt> and <tt>reverse_merge!</tt></h5>
|
2350
|
+
<p>In case of collision the key in the hash of the argument wins in <tt>merge</tt>. You can support option hashes with default values in a compact way with this idiom:</p>
|
2351
|
+
<div class="code_container">
|
2352
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2353
|
+
options = {:length => 30, :omission => "..."}.merge(options)
|
2354
|
+
</pre>
|
2355
|
+
</div>
|
2356
|
+
<p>Active Support defines <tt>reverse_merge</tt> in case you prefer this alternative notation:</p>
|
2357
|
+
<div class="code_container">
|
2358
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2359
|
+
options = options.reverse_merge(:length => 30, :omission => "...")
|
2360
|
+
</pre>
|
2361
|
+
</div>
|
2362
|
+
<p>And a bang version <tt>reverse_merge!</tt> that performs the merge in place:</p>
|
2363
|
+
<div class="code_container">
|
2364
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2365
|
+
options.reverse_merge!(:length => 30, :omission => "...")
|
2366
|
+
</pre>
|
2367
|
+
</div>
|
2368
|
+
<div class="warning"><p>Take into account that <tt>reverse_merge!</tt> may change the hash in the caller, which may or may not be a good idea.</p></div>
|
2369
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/hash/reverse_merge.rb</tt>.</p></div>
|
2370
|
+
<h5 id="reverse_update">12.2.2 <tt>reverse_update</tt></h5>
|
2371
|
+
<p>The method <tt>reverse_update</tt> is an alias for <tt>reverse_merge!</tt>, explained above.</p>
|
2372
|
+
<div class="warning"><p>Note that <tt>reverse_update</tt> has no bang.</p></div>
|
2373
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/hash/reverse_merge.rb</tt>.</p></div>
|
2374
|
+
<h5 id="deep_merge-and-deep_merge">12.2.3 <tt>deep_merge</tt> and <tt>deep_merge!</tt></h5>
|
2375
|
+
<p>As you can see in the previous example if a key is found in both hashes the value in the one in the argument wins.</p>
|
2376
|
+
<p>Active Support defines <tt>Hash#deep_merge</tt>. In a deep merge, if a key is found in both hashes and their values are hashes in turn, then their <em>merge</em> becomes the value in the resulting hash:</p>
|
2377
|
+
<div class="code_container">
|
2378
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2379
|
+
{:a => {:b => 1}}.deep_merge(:a => {:c => 2})
|
2380
|
+
# => {:a => {:b => 1, :c => 2}}
|
2381
|
+
</pre>
|
2382
|
+
</div>
|
2383
|
+
<p>The method <tt>deep_merge!</tt> performs a deep merge in place.</p>
|
2384
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/hash/deep_merge.rb</tt>.</p></div>
|
2385
|
+
<h4 id="diffing">12.3 Diffing</h4>
|
2386
|
+
<p>The method <tt>diff</tt> returns a hash that represents a diff of the receiver and the argument with the following logic:</p>
|
2387
|
+
<ul>
|
2388
|
+
<li>Pairs <tt>key</tt>, <tt>value</tt> that exist in both hashes do not belong to the diff hash.</li>
|
2389
|
+
</ul>
|
2390
|
+
<ul>
|
2391
|
+
<li>If both hashes have <tt>key</tt>, but with different values, the pair in the receiver wins.</li>
|
2392
|
+
</ul>
|
2393
|
+
<ul>
|
2394
|
+
<li>The rest is just merged.</li>
|
2395
|
+
</ul>
|
2396
|
+
<div class="code_container">
|
2397
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2398
|
+
{:a => 1}.diff(:a => 1)
|
2399
|
+
# => {}, first rule
|
2400
|
+
|
2401
|
+
{:a => 1}.diff(:a => 2)
|
2402
|
+
# => {:a => 1}, second rule
|
2403
|
+
|
2404
|
+
{:a => 1}.diff(:b => 2)
|
2405
|
+
# => {:a => 1, :b => 2}, third rule
|
2406
|
+
|
2407
|
+
{:a => 1, :b => 2, :c => 3}.diff(:b => 1, :c => 3, :d => 4)
|
2408
|
+
# => {:a => 1, :b => 2, :d => 4}, all rules
|
2409
|
+
|
2410
|
+
{}.diff({}) # => {}
|
2411
|
+
{:a => 1}.diff({}) # => {:a => 1}
|
2412
|
+
{}.diff(:a => 1) # => {:a => 1}
|
2413
|
+
</pre>
|
2414
|
+
</div>
|
2415
|
+
<p>An important property of this diff hash is that you can retrieve the original hash by applying <tt>diff</tt> twice:</p>
|
2416
|
+
<div class="code_container">
|
2417
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2418
|
+
hash.diff(hash2).diff(hash2) == hash
|
2419
|
+
</pre>
|
2420
|
+
</div>
|
2421
|
+
<p>Diffing hashes may be useful for error messages related to expected option hashes for example.</p>
|
2422
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/hash/diff.rb</tt>.</p></div>
|
2423
|
+
<h4 id="working-with-keys">12.4 Working with Keys</h4>
|
2424
|
+
<h5 id="except-and-except">12.4.1 <tt>except</tt> and <tt>except!</tt></h5>
|
2425
|
+
<p>The method <tt>except</tt> returns a hash with the keys in the argument list removed, if present:</p>
|
2426
|
+
<div class="code_container">
|
2427
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2428
|
+
{:a => 1, :b => 2}.except(:a) # => {:b => 2}
|
2429
|
+
</pre>
|
2430
|
+
</div>
|
2431
|
+
<p>If the receiver responds to <tt>convert_key</tt>, the method is called on each of the arguments. This allows <tt>except</tt> to play nice with hashes with indifferent access for instance:</p>
|
2432
|
+
<div class="code_container">
|
2433
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2434
|
+
{:a => 1}.with_indifferent_access.except(:a) # => {}
|
2435
|
+
{:a => 1}.with_indifferent_access.except("a") # => {}
|
2436
|
+
</pre>
|
2437
|
+
</div>
|
2438
|
+
<p>The method <tt>except</tt> may come in handy for example when you want to protect some parameter that can’t be globally protected with <tt>attr_protected</tt>:</p>
|
2439
|
+
<div class="code_container">
|
2440
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2441
|
+
params[:account] = params[:account].except(:plan_id) unless admin?
|
2442
|
+
@account.update_attributes(params[:account])
|
2443
|
+
</pre>
|
2444
|
+
</div>
|
2445
|
+
<p>There’s also the bang variant <tt>except!</tt> that removes keys in the very receiver.</p>
|
2446
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/hash/except.rb</tt>.</p></div>
|
2447
|
+
<h5 id="stringify_keys-and-stringify_keys">12.4.2 <tt>stringify_keys</tt> and <tt>stringify_keys!</tt></h5>
|
2448
|
+
<p>The method <tt>stringify_keys</tt> returns a hash that has a stringified version of the keys in the receiver. It does so by sending <tt>to_s</tt> to them:</p>
|
2449
|
+
<div class="code_container">
|
2450
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2451
|
+
{nil => nil, 1 => 1, :a => :a}.stringify_keys
|
2452
|
+
# => {"" => nil, "a" => :a, "1" => 1}
|
2453
|
+
</pre>
|
2454
|
+
</div>
|
2455
|
+
<p>The result in case of collision is undefined:</p>
|
2456
|
+
<div class="code_container">
|
2457
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2458
|
+
{"a" => 1, :a => 2}.stringify_keys
|
2459
|
+
# => {"a" => 2}, in my test, can't rely on this result though
|
2460
|
+
</pre>
|
2461
|
+
</div>
|
2462
|
+
<p>This method may be useful for example to easily accept both symbols and strings as options. For instance <tt>ActionView::Helpers::FormHelper</tt> defines:</p>
|
2463
|
+
<div class="code_container">
|
2464
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2465
|
+
def to_check_box_tag(options = {}, checked_value = "1", unchecked_value = "0")
|
2466
|
+
options = options.stringify_keys
|
2467
|
+
options["type"] = "checkbox"
|
2468
|
+
...
|
2469
|
+
end
|
2470
|
+
</pre>
|
2471
|
+
</div>
|
2472
|
+
<p>The second line can safely access the “type” key, and let the user to pass either <tt>:type</tt> or “type”.</p>
|
2473
|
+
<p>There’s also the bang variant <tt>stringify_keys!</tt> that stringifies keys in the very receiver.</p>
|
2474
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/hash/keys.rb</tt>.</p></div>
|
2475
|
+
<h5 id="symbolize_keys-and-symbolize_keys">12.4.3 <tt>symbolize_keys</tt> and <tt>symbolize_keys!</tt></h5>
|
2476
|
+
<p>The method <tt>symbolize_keys</tt> returns a hash that has a symbolized version of the keys in the receiver, where possible. It does so by sending <tt>to_sym</tt> to them:</p>
|
2477
|
+
<div class="code_container">
|
2478
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2479
|
+
{nil => nil, 1 => 1, "a" => "a"}.symbolize_keys
|
2480
|
+
# => {1 => 1, nil => nil, :a => "a"}
|
2481
|
+
</pre>
|
2482
|
+
</div>
|
2483
|
+
<div class="warning"><p>Note in the previous example only one key was symbolized.</p></div>
|
2484
|
+
<p>The result in case of collision is undefined:</p>
|
2485
|
+
<div class="code_container">
|
2486
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2487
|
+
{"a" => 1, :a => 2}.symbolize_keys
|
2488
|
+
# => {:a => 2}, in my test, can't rely on this result though
|
2489
|
+
</pre>
|
2490
|
+
</div>
|
2491
|
+
<p>This method may be useful for example to easily accept both symbols and strings as options. For instance <tt>ActionController::UrlRewriter</tt> defines</p>
|
2492
|
+
<div class="code_container">
|
2493
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2494
|
+
def rewrite_path(options)
|
2495
|
+
options = options.symbolize_keys
|
2496
|
+
options.update(options[:params].symbolize_keys) if options[:params]
|
2497
|
+
...
|
2498
|
+
end
|
2499
|
+
</pre>
|
2500
|
+
</div>
|
2501
|
+
<p>The second line can safely access the <tt>:params</tt> key, and let the user to pass either <tt>:params</tt> or “params”.</p>
|
2502
|
+
<p>There’s also the bang variant <tt>symbolize_keys!</tt> that symbolizes keys in the very receiver.</p>
|
2503
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/hash/keys.rb</tt>.</p></div>
|
2504
|
+
<h5 id="to_options-and-to_options">12.4.4 <tt>to_options</tt> and <tt>to_options!</tt></h5>
|
2505
|
+
<p>The methods <tt>to_options</tt> and <tt>to_options!</tt> are respectively aliases of <tt>symbolize_keys</tt> and <tt>symbolize_keys!</tt>.</p>
|
2506
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/hash/keys.rb</tt>.</p></div>
|
2507
|
+
<h5 id="assert_valid_keys">12.4.5 <tt>assert_valid_keys</tt></h5>
|
2508
|
+
<p>The method <tt>assert_valid_keys</tt> receives an arbitrary number of arguments, and checks whether the receiver has any key outside that white list. If it does <tt>ArgumentError</tt> is raised.</p>
|
2509
|
+
<div class="code_container">
|
2510
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2511
|
+
{:a => 1}.assert_valid_keys(:a) # passes
|
2512
|
+
{:a => 1}.assert_valid_keys("a") # ArgumentError
|
2513
|
+
</pre>
|
2514
|
+
</div>
|
2515
|
+
<p>Active Record does not accept unknown options when building associations for example. It implements that control via <tt>assert_valid_keys</tt>:</p>
|
2516
|
+
<div class="code_container">
|
2517
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2518
|
+
mattr_accessor :valid_keys_for_has_many_association
|
2519
|
+
@@valid_keys_for_has_many_association = [
|
2520
|
+
:class_name, :table_name, :foreign_key, :primary_key,
|
2521
|
+
:dependent,
|
2522
|
+
:select, :conditions, :include, :order, :group, :having, :limit, :offset,
|
2523
|
+
:as, :through, :source, :source_type,
|
2524
|
+
:uniq,
|
2525
|
+
:finder_sql, :counter_sql,
|
2526
|
+
:before_add, :after_add, :before_remove, :after_remove,
|
2527
|
+
:extend, :readonly,
|
2528
|
+
:validate, :inverse_of
|
2529
|
+
]
|
2530
|
+
|
2531
|
+
def create_has_many_reflection(association_id, options, &extension)
|
2532
|
+
options.assert_valid_keys(valid_keys_for_has_many_association)
|
2533
|
+
...
|
2534
|
+
end
|
2535
|
+
</pre>
|
2536
|
+
</div>
|
2537
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/hash/keys.rb</tt>.</p></div>
|
2538
|
+
<h4 id="slicing">12.5 Slicing</h4>
|
2539
|
+
<p>Ruby has built-in support for taking slices out of strings and arrays. Active Support extends slicing to hashes:</p>
|
2540
|
+
<div class="code_container">
|
2541
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2542
|
+
{:a => 1, :b => 2, :c => 3}.slice(:a, :c)
|
2543
|
+
# => {:c => 3, :a => 1}
|
2544
|
+
|
2545
|
+
{:a => 1, :b => 2, :c => 3}.slice(:b, :X)
|
2546
|
+
# => {:b => 2} # non-existing keys are ignored
|
2547
|
+
</pre>
|
2548
|
+
</div>
|
2549
|
+
<p>If the receiver responds to <tt>convert_key</tt> keys are normalized:</p>
|
2550
|
+
<div class="code_container">
|
2551
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2552
|
+
{:a => 1, :b => 2}.with_indifferent_access.slice("a")
|
2553
|
+
# => {:a => 1}
|
2554
|
+
</pre>
|
2555
|
+
</div>
|
2556
|
+
<div class="note"><p>Slicing may come in handy for sanitizing option hashes with a white list of keys.</p></div>
|
2557
|
+
<p>There’s also <tt>slice!</tt> which in addition to perform a slice in place returns what’s removed:</p>
|
2558
|
+
<div class="code_container">
|
2559
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2560
|
+
hash = {:a => 1, :b => 2}
|
2561
|
+
rest = hash.slice!(:a) # => {:b => 2}
|
2562
|
+
hash # => {:a => 1}
|
2563
|
+
</pre>
|
2564
|
+
</div>
|
2565
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/hash/slice.rb</tt>.</p></div>
|
2566
|
+
<h4 id="extracting">12.6 Extracting</h4>
|
2567
|
+
<p>The method <tt>extract!</tt> removes and returns the key/value pairs matching the given keys.</p>
|
2568
|
+
<div class="code_container">
|
2569
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2570
|
+
hash = {:a => 1, :b => 2}
|
2571
|
+
rest = hash.extract!(:a) # => {:a => 1}
|
2572
|
+
hash # => {:b => 2}
|
2573
|
+
</pre>
|
2574
|
+
</div>
|
2575
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/hash/slice.rb</tt>.</p></div>
|
2576
|
+
<h4 id="indifferent-access">12.7 Indifferent Access</h4>
|
2577
|
+
<p>The method <tt>with_indifferent_access</tt> returns an <tt>ActiveSupport::HashWithIndifferentAccess</tt> out of its receiver:</p>
|
2578
|
+
<div class="code_container">
|
2579
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2580
|
+
{:a => 1}.with_indifferent_access["a"] # => 1
|
2581
|
+
</pre>
|
2582
|
+
</div>
|
2583
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/hash/indifferent_access.rb</tt>.</p></div>
|
2584
|
+
<h3 id="extensions-to-regexp">13 Extensions to <tt>Regexp</tt></h3>
|
2585
|
+
<h4 id="multiline">13.1 <tt>multiline?</tt></h4>
|
2586
|
+
<p>The method <tt>multiline?</tt> says whether a regexp has the <tt>/m</tt> flag set, that is, whether the dot matches newlines.</p>
|
2587
|
+
<div class="code_container">
|
2588
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2589
|
+
%r{.}.multiline? # => false
|
2590
|
+
%r{.}m.multiline? # => true
|
2591
|
+
|
2592
|
+
Regexp.new('.').multiline? # => false
|
2593
|
+
Regexp.new('.', Regexp::MULTILINE).multiline? # => true
|
2594
|
+
</pre>
|
2595
|
+
</div>
|
2596
|
+
<p>Rails uses this method in a single place, also in the routing code. Multiline regexps are disallowed for route requirements and this flag eases enforcing that constraint.</p>
|
2597
|
+
<div class="code_container">
|
2598
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2599
|
+
def assign_route_options(segments, defaults, requirements)
|
2600
|
+
...
|
2601
|
+
if requirement.multiline?
|
2602
|
+
raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}"
|
2603
|
+
end
|
2604
|
+
...
|
2605
|
+
end
|
2606
|
+
</pre>
|
2607
|
+
</div>
|
2608
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/regexp.rb</tt>.</p></div>
|
2609
|
+
<h3 id="extensions-to-range">14 Extensions to <tt>Range</tt></h3>
|
2610
|
+
<h4 id="to_s">14.1 <tt>to_s</tt></h4>
|
2611
|
+
<p>Active Support extends the method <tt>Range#to_s</tt> so that it understands an optional format argument. As of this writing the only supported non-default format is <tt>:db</tt>:</p>
|
2612
|
+
<div class="code_container">
|
2613
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2614
|
+
(Date.today..Date.tomorrow).to_s
|
2615
|
+
# => "2009-10-25..2009-10-26"
|
2616
|
+
|
2617
|
+
(Date.today..Date.tomorrow).to_s(:db)
|
2618
|
+
# => "BETWEEN '2009-10-25' AND '2009-10-26'"
|
2619
|
+
</pre>
|
2620
|
+
</div>
|
2621
|
+
<p>As the example depicts, the <tt>:db</tt> format generates a <tt>BETWEEN</tt> <span class="caps">SQL</span> clause. That is used by Active Record in its support for range values in conditions.</p>
|
2622
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/range/conversions.rb</tt>.</p></div>
|
2623
|
+
<h4 id="step">14.2 <tt>step</tt></h4>
|
2624
|
+
<p>Active Support extends the method <tt>Range#step</tt> so that it can be invoked without a block:</p>
|
2625
|
+
<div class="code_container">
|
2626
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2627
|
+
(1..10).step(2) # => [1, 3, 5, 7, 9]
|
2628
|
+
</pre>
|
2629
|
+
</div>
|
2630
|
+
<p>As the example shows, in that case the method returns an array with the corresponding elements.</p>
|
2631
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/range/blockless_step.rb</tt>.</p></div>
|
2632
|
+
<h4 id="include">14.3 <tt>include?</tt></h4>
|
2633
|
+
<p>The method <tt>Range#include?</tt> says whether some value falls between the ends of a given instance:</p>
|
2634
|
+
<div class="code_container">
|
2635
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2636
|
+
(2..3).include?(Math::E) # => true
|
2637
|
+
</pre>
|
2638
|
+
</div>
|
2639
|
+
<p>Active Support extends this method so that the argument may be another range in turn. In that case we test whether the ends of the argument range belong to the receiver themselves:</p>
|
2640
|
+
<div class="code_container">
|
2641
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2642
|
+
(1..10).include?(3..7) # => true
|
2643
|
+
(1..10).include?(0..7) # => false
|
2644
|
+
(1..10).include?(3..11) # => false
|
2645
|
+
(1...9).include?(3..9) # => false
|
2646
|
+
</pre>
|
2647
|
+
</div>
|
2648
|
+
<div class="warning"><p>The original <tt>Range#include?</tt> is still the one aliased to <tt>Range#===</tt>.</p></div>
|
2649
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/range/include_range.rb</tt>.</p></div>
|
2650
|
+
<h4 id="cover">14.4 <tt>cover?</tt></h4>
|
2651
|
+
<p>Ruby 1.9 provides <tt>cover?</tt>, and Active Support defines it for previous versions as an alias for <tt>include?</tt>.</p>
|
2652
|
+
<p>The method <tt>include?</tt> in Ruby 1.9 is different from the one in 1.8 for non-numeric ranges: instead of being based on comparisons between the value and the range’s endpoints, it walks the range with <tt>succ</tt> looking for value. This works better for ranges with holes, but it has different complexity and may not finish in some other cases.</p>
|
2653
|
+
<p>In Ruby 1.9 the old behavior is still available in the new <tt>cover?</tt>, which Active Support backports for forward compatibility. For example, Rails uses <tt>cover?</tt> for ranges in <tt>validates_inclusion_of</tt>.</p>
|
2654
|
+
<h4 id="overlaps">14.5 <tt>overlaps?</tt></h4>
|
2655
|
+
<p>The method <tt>Range#overlaps?</tt> says whether any two given ranges have non-void intersection:</p>
|
2656
|
+
<div class="code_container">
|
2657
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2658
|
+
(1..10).overlaps?(7..11) # => true
|
2659
|
+
(1..10).overlaps?(0..7) # => true
|
2660
|
+
(1..10).overlaps?(11..27) # => false
|
2661
|
+
</pre>
|
2662
|
+
</div>
|
2663
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/range/overlaps.rb</tt>.</p></div>
|
2664
|
+
<h3 id="extensions-to-proc">15 Extensions to <tt>Proc</tt></h3>
|
2665
|
+
<h4 id="bind">15.1 <tt>bind</tt></h4>
|
2666
|
+
<p>As you surely know Ruby has an <tt>UnboundMethod</tt> class whose instances are methods that belong to the limbo of methods without a self. The method <tt>Module#instance_method</tt> returns an unbound method for example:</p>
|
2667
|
+
<div class="code_container">
|
2668
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2669
|
+
Hash.instance_method(:delete) # => #<UnboundMethod: Hash#delete>
|
2670
|
+
</pre>
|
2671
|
+
</div>
|
2672
|
+
<p>An unbound method is not callable as is, you need to bind it first to an object with <tt>bind</tt>:</p>
|
2673
|
+
<div class="code_container">
|
2674
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2675
|
+
clear = Hash.instance_method(:clear)
|
2676
|
+
clear.bind({:a => 1}).call # => {}
|
2677
|
+
</pre>
|
2678
|
+
</div>
|
2679
|
+
<p>Active Support defines <tt>Proc#bind</tt> with an analogous purpose:</p>
|
2680
|
+
<div class="code_container">
|
2681
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2682
|
+
Proc.new { size }.bind([]).call # => 0
|
2683
|
+
</pre>
|
2684
|
+
</div>
|
2685
|
+
<p>As you see that’s callable and bound to the argument, the return value is indeed a <tt>Method</tt>.</p>
|
2686
|
+
<div class="note"><p>To do so <tt>Proc#bind</tt> actually creates a method under the hood. If you ever see a method with a weird name like <tt>__bind_1256598120_237302</tt> in a stack trace you know now where it comes from.</p></div>
|
2687
|
+
<p>Action Pack uses this trick in <tt>rescue_from</tt> for example, which accepts the name of a method and also a proc as callbacks for a given rescued exception. It has to call them in either case, so a bound method is returned by <tt>handler_for_rescue</tt>, thus simplifying the code in the caller:</p>
|
2688
|
+
<div class="code_container">
|
2689
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2690
|
+
def handler_for_rescue(exception)
|
2691
|
+
_, rescuer = Array(rescue_handlers).reverse.detect do |klass_name, handler|
|
2692
|
+
...
|
2693
|
+
end
|
2694
|
+
|
2695
|
+
case rescuer
|
2696
|
+
when Symbol
|
2697
|
+
method(rescuer)
|
2698
|
+
when Proc
|
2699
|
+
rescuer.bind(self)
|
2700
|
+
end
|
2701
|
+
end
|
2702
|
+
</pre>
|
2703
|
+
</div>
|
2704
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/proc.rb</tt>.</p></div>
|
2705
|
+
<h3 id="extensions-to-date">16 Extensions to <tt>Date</tt></h3>
|
2706
|
+
<h4 id="calculations">16.1 Calculations</h4>
|
2707
|
+
<div class="note"><p>All the following methods are defined in <tt>active_support/core_ext/date/calculations.rb</tt>.</p></div>
|
2708
|
+
<div class="info"><p>The following calculation methods have edge cases in October 1582, since days 5..14 just do not exist. This guide does not document their behavior around those days for brevity, but it is enough to say that they do what you would expect. That is, <tt>Date.new(1582, 10, 4).tomorrow</tt> returns <tt>Date.new(1582, 10, 15)</tt> and so on. Please check <tt>test/core_ext/date_ext_test.rb</tt> in the Active Support test suite for expected behavior.</p></div>
|
2709
|
+
<h5 id="date-current">16.1.1 <tt>Date.current</tt></h5>
|
2710
|
+
<p>Active Support defines <tt>Date.current</tt> to be today in the current time zone. That’s like <tt>Date.today</tt>, except that it honors the user time zone, if defined. It also defines <tt>Date.yesterday</tt> and <tt>Date.tomorrow</tt>, and the instance predicates <tt>past?</tt>, <tt>today?</tt>, and <tt>future?</tt>, all of them relative to <tt>Date.current</tt>.</p>
|
2711
|
+
<p>When making Date comparisons using methods which honor the user time zone, make sure to use <tt>Date.current</tt> and not <tt>Date.today</tt>. There are cases where the user time zone might be in the future compared to the system time zone, which <tt>Date.today</tt> uses by default. This means <tt>Date.today</tt> may equal <tt>Date.yesterday</tt>.</p>
|
2712
|
+
<h5 id="named-dates">16.1.2 Named dates</h5>
|
2713
|
+
<h6 id="prev_year-next_year">16.1.2.1 <tt>prev_year</tt>, <tt>next_year</tt></h6>
|
2714
|
+
<p>In Ruby 1.9 <tt>prev_year</tt> and <tt>next_year</tt> return a date with the same day/month in the last or next year:</p>
|
2715
|
+
<div class="code_container">
|
2716
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2717
|
+
d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
|
2718
|
+
d.prev_year # => Fri, 08 May 2009
|
2719
|
+
d.next_year # => Sun, 08 May 2011
|
2720
|
+
</pre>
|
2721
|
+
</div>
|
2722
|
+
<p>If date is the 29th of February of a leap year, you obtain the 28th:</p>
|
2723
|
+
<div class="code_container">
|
2724
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2725
|
+
d = Date.new(2000, 2, 29) # => Tue, 29 Feb 2000
|
2726
|
+
d.prev_year # => Sun, 28 Feb 1999
|
2727
|
+
d.next_year # => Wed, 28 Feb 2001
|
2728
|
+
</pre>
|
2729
|
+
</div>
|
2730
|
+
<p>Active Support defines these methods as well for Ruby 1.8.</p>
|
2731
|
+
<h6 id="prev_month-next_month">16.1.2.2 <tt>prev_month</tt>, <tt>next_month</tt></h6>
|
2732
|
+
<p>In Ruby 1.9 <tt>prev_month</tt> and <tt>next_month</tt> return the date with the same day in the last or next month:</p>
|
2733
|
+
<div class="code_container">
|
2734
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2735
|
+
d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
|
2736
|
+
d.prev_month # => Thu, 08 Apr 2010
|
2737
|
+
d.next_month # => Tue, 08 Jun 2010
|
2738
|
+
</pre>
|
2739
|
+
</div>
|
2740
|
+
<p>If such a day does not exist, the last day of the corresponding month is returned:</p>
|
2741
|
+
<div class="code_container">
|
2742
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2743
|
+
Date.new(2000, 5, 31).prev_month # => Sun, 30 Apr 2000
|
2744
|
+
Date.new(2000, 3, 31).prev_month # => Tue, 29 Feb 2000
|
2745
|
+
Date.new(2000, 5, 31).next_month # => Fri, 30 Jun 2000
|
2746
|
+
Date.new(2000, 1, 31).next_month # => Tue, 29 Feb 2000
|
2747
|
+
</pre>
|
2748
|
+
</div>
|
2749
|
+
<p>Active Support defines these methods as well for Ruby 1.8.</p>
|
2750
|
+
<h6 id="beginning_of_week-end_of_week">16.1.2.3 <tt>beginning_of_week</tt>, <tt>end_of_week</tt></h6>
|
2751
|
+
<p>The methods <tt>beginning_of_week</tt> and <tt>end_of_week</tt> return the dates for the beginning and end of week, assuming weeks start on Monday:</p>
|
2752
|
+
<div class="code_container">
|
2753
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2754
|
+
d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
|
2755
|
+
d.beginning_of_week # => Mon, 03 May 2010
|
2756
|
+
d.end_of_week # => Sun, 09 May 2010
|
2757
|
+
</pre>
|
2758
|
+
</div>
|
2759
|
+
<p><tt>beginning_of_week</tt> is aliased to <tt>monday</tt> and <tt>at_beginning_of_week</tt>. <tt>end_of_week</tt> is aliased to <tt>sunday</tt> and <tt>at_end_of_week</tt>.</p>
|
2760
|
+
<h6 id="prev_week-next_week">16.1.2.4 <tt>prev_week</tt>, <tt>next_week</tt></h6>
|
2761
|
+
<p>The method <tt>next_week</tt> receives a symbol with a day name in English (in lowercase, default is <tt>:monday</tt>) and it returns the date corresponding to that day:</p>
|
2762
|
+
<div class="code_container">
|
2763
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2764
|
+
d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
|
2765
|
+
d.next_week # => Mon, 10 May 2010
|
2766
|
+
d.next_week(:saturday) # => Sat, 15 May 2010
|
2767
|
+
</pre>
|
2768
|
+
</div>
|
2769
|
+
<p>The method <tt>prev_week</tt> is analogous:</p>
|
2770
|
+
<div class="code_container">
|
2771
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2772
|
+
d.prev_week # => Mon, 26 Apr 2010
|
2773
|
+
d.prev_week(:saturday) # => Sat, 01 May 2010
|
2774
|
+
d.prev_week(:friday) # => Fri, 30 Apr 2010
|
2775
|
+
</pre>
|
2776
|
+
</div>
|
2777
|
+
<h6 id="beginning_of_month-end_of_month">16.1.2.5 <tt>beginning_of_month</tt>, <tt>end_of_month</tt></h6>
|
2778
|
+
<p>The methods <tt>beginning_of_month</tt> and <tt>end_of_month</tt> return the dates for the beginning and end of the month:</p>
|
2779
|
+
<div class="code_container">
|
2780
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2781
|
+
d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
|
2782
|
+
d.beginning_of_month # => Sat, 01 May 2010
|
2783
|
+
d.end_of_month # => Mon, 31 May 2010
|
2784
|
+
</pre>
|
2785
|
+
</div>
|
2786
|
+
<p><tt>beginning_of_month</tt> is aliased to <tt>at_beginning_of_month</tt>, and <tt>end_of_month</tt> is aliased to <tt>at_end_of_month</tt>.</p>
|
2787
|
+
<h6 id="beginning_of_quarter-end_of_quarter">16.1.2.6 <tt>beginning_of_quarter</tt>, <tt>end_of_quarter</tt></h6>
|
2788
|
+
<p>The methods <tt>beginning_of_quarter</tt> and <tt>end_of_quarter</tt> return the dates for the beginning and end of the quarter of the receiver’s calendar year:</p>
|
2789
|
+
<div class="code_container">
|
2790
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2791
|
+
d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
|
2792
|
+
d.beginning_of_quarter # => Thu, 01 Apr 2010
|
2793
|
+
d.end_of_quarter # => Wed, 30 Jun 2010
|
2794
|
+
</pre>
|
2795
|
+
</div>
|
2796
|
+
<p><tt>beginning_of_quarter</tt> is aliased to <tt>at_beginning_of_quarter</tt>, and <tt>end_of_quarter</tt> is aliased to <tt>at_end_of_quarter</tt>.</p>
|
2797
|
+
<h6 id="beginning_of_year-end_of_year">16.1.2.7 <tt>beginning_of_year</tt>, <tt>end_of_year</tt></h6>
|
2798
|
+
<p>The methods <tt>beginning_of_year</tt> and <tt>end_of_year</tt> return the dates for the beginning and end of the year:</p>
|
2799
|
+
<div class="code_container">
|
2800
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2801
|
+
d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
|
2802
|
+
d.beginning_of_year # => Fri, 01 Jan 2010
|
2803
|
+
d.end_of_year # => Fri, 31 Dec 2010
|
2804
|
+
</pre>
|
2805
|
+
</div>
|
2806
|
+
<p><tt>beginning_of_year</tt> is aliased to <tt>at_beginning_of_year</tt>, and <tt>end_of_year</tt> is aliased to <tt>at_end_of_year</tt>.</p>
|
2807
|
+
<h5 id="other-date-computations">16.1.3 Other Date Computations</h5>
|
2808
|
+
<h6 id="years_ago-years_since">16.1.3.1 <tt>years_ago</tt>, <tt>years_since</tt></h6>
|
2809
|
+
<p>The method <tt>years_ago</tt> receives a number of years and returns the same date those many years ago:</p>
|
2810
|
+
<div class="code_container">
|
2811
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2812
|
+
date = Date.new(2010, 6, 7)
|
2813
|
+
date.years_ago(10) # => Wed, 07 Jun 2000
|
2814
|
+
</pre>
|
2815
|
+
</div>
|
2816
|
+
<p><tt>years_since</tt> moves forward in time:</p>
|
2817
|
+
<div class="code_container">
|
2818
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2819
|
+
date = Date.new(2010, 6, 7)
|
2820
|
+
date.years_since(10) # => Sun, 07 Jun 2020
|
2821
|
+
</pre>
|
2822
|
+
</div>
|
2823
|
+
<p>If such a day does not exist, the last day of the corresponding month is returned:</p>
|
2824
|
+
<div class="code_container">
|
2825
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2826
|
+
Date.new(2012, 2, 29).years_ago(3) # => Sat, 28 Feb 2009
|
2827
|
+
Date.new(2012, 2, 29).years_since(3) # => Sat, 28 Feb 2015
|
2828
|
+
</pre>
|
2829
|
+
</div>
|
2830
|
+
<h6 id="months_ago-months_since">16.1.3.2 <tt>months_ago</tt>, <tt>months_since</tt></h6>
|
2831
|
+
<p>The methods <tt>months_ago</tt> and <tt>months_since</tt> work analogously for months:</p>
|
2832
|
+
<div class="code_container">
|
2833
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2834
|
+
Date.new(2010, 4, 30).months_ago(2) # => Sun, 28 Feb 2010
|
2835
|
+
Date.new(2010, 4, 30).months_since(2) # => Wed, 30 Jun 2010
|
2836
|
+
</pre>
|
2837
|
+
</div>
|
2838
|
+
<p>If such a day does not exist, the last day of the corresponding month is returned:</p>
|
2839
|
+
<div class="code_container">
|
2840
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2841
|
+
Date.new(2010, 4, 30).months_ago(2) # => Sun, 28 Feb 2010
|
2842
|
+
Date.new(2009, 12, 31).months_since(2) # => Sun, 28 Feb 2010
|
2843
|
+
</pre>
|
2844
|
+
</div>
|
2845
|
+
<h6 id="weeks_ago">16.1.3.3 <tt>weeks_ago</tt></h6>
|
2846
|
+
<p>The method <tt>weeks_ago</tt> works analogously for weeks:</p>
|
2847
|
+
<div class="code_container">
|
2848
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2849
|
+
Date.new(2010, 5, 24).weeks_ago(1) # => Mon, 17 May 2010
|
2850
|
+
Date.new(2010, 5, 24).weeks_ago(2) # => Mon, 10 May 2010
|
2851
|
+
</pre>
|
2852
|
+
</div>
|
2853
|
+
<h6 id="advance">16.1.3.4 <tt>advance</tt></h6>
|
2854
|
+
<p>The most generic way to jump to other days is <tt>advance</tt>. This method receives a hash with keys <tt>:years</tt>, <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, and returns a date advanced as much as the present keys indicate:</p>
|
2855
|
+
<div class="code_container">
|
2856
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2857
|
+
date = Date.new(2010, 6, 6)
|
2858
|
+
date.advance(:years => 1, :weeks => 2) # => Mon, 20 Jun 2011
|
2859
|
+
date.advance(:months => 2, :days => -2) # => Wed, 04 Aug 2010
|
2860
|
+
</pre>
|
2861
|
+
</div>
|
2862
|
+
<p>Note in the previous example that increments may be negative.</p>
|
2863
|
+
<p>To perform the computation the method first increments years, then months, then weeks, and finally days. This order is important towards the end of months. Say for example we are at the end of February of 2010, and we want to move one month and one day forward.</p>
|
2864
|
+
<p>The method <tt>advance</tt> advances first one month, and then one day, the result is:</p>
|
2865
|
+
<div class="code_container">
|
2866
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2867
|
+
Date.new(2010, 2, 28).advance(:months => 1, :days => 1)
|
2868
|
+
# => Sun, 29 Mar 2010
|
2869
|
+
</pre>
|
2870
|
+
</div>
|
2871
|
+
<p>While if it did it the other way around the result would be different:</p>
|
2872
|
+
<div class="code_container">
|
2873
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2874
|
+
Date.new(2010, 2, 28).advance(:days => 1).advance(:months => 1)
|
2875
|
+
# => Thu, 01 Apr 2010
|
2876
|
+
</pre>
|
2877
|
+
</div>
|
2878
|
+
<h5 id="changing-components">16.1.4 Changing Components</h5>
|
2879
|
+
<p>The method <tt>change</tt> allows you to get a new date which is the same as the receiver except for the given year, month, or day:</p>
|
2880
|
+
<div class="code_container">
|
2881
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2882
|
+
Date.new(2010, 12, 23).change(:year => 2011, :month => 11)
|
2883
|
+
# => Wed, 23 Nov 2011
|
2884
|
+
</pre>
|
2885
|
+
</div>
|
2886
|
+
<p>This method is not tolerant to non-existing dates, if the change is invalid <tt>ArgumentError</tt> is raised:</p>
|
2887
|
+
<div class="code_container">
|
2888
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2889
|
+
Date.new(2010, 1, 31).change(:month => 2)
|
2890
|
+
# => ArgumentError: invalid date
|
2891
|
+
</pre>
|
2892
|
+
</div>
|
2893
|
+
<h5 id="date-durations">16.1.5 Durations</h5>
|
2894
|
+
<p>Durations can be added to and subtracted from dates:</p>
|
2895
|
+
<div class="code_container">
|
2896
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2897
|
+
d = Date.current
|
2898
|
+
# => Mon, 09 Aug 2010
|
2899
|
+
d + 1.year
|
2900
|
+
# => Tue, 09 Aug 2011
|
2901
|
+
d - 3.hours
|
2902
|
+
# => Sun, 08 Aug 2010 21:00:00 UTC +00:00
|
2903
|
+
</pre>
|
2904
|
+
</div>
|
2905
|
+
<p>They translate to calls to <tt>since</tt> or <tt>advance</tt>. For example here we get the correct jump in the calendar reform:</p>
|
2906
|
+
<div class="code_container">
|
2907
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2908
|
+
Date.new(1582, 10, 4) + 1.day
|
2909
|
+
# => Fri, 15 Oct 1582
|
2910
|
+
</pre>
|
2911
|
+
</div>
|
2912
|
+
<h5 id="timestamps">16.1.6 Timestamps</h5>
|
2913
|
+
<div class="info"><p>The following methods return a <tt>Time</tt> object if possible, otherwise a <tt>DateTime</tt>. If set, they honor the user time zone.</p></div>
|
2914
|
+
<h6 id="beginning_of_day-end_of_day">16.1.6.1 <tt>beginning_of_day</tt>, <tt>end_of_day</tt></h6>
|
2915
|
+
<p>The method <tt>beginning_of_day</tt> returns a timestamp at the beginning of the day (00:00:00):</p>
|
2916
|
+
<div class="code_container">
|
2917
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2918
|
+
date = Date.new(2010, 6, 7)
|
2919
|
+
date.beginning_of_day # => Sun Jun 07 00:00:00 +0200 2010
|
2920
|
+
</pre>
|
2921
|
+
</div>
|
2922
|
+
<p>The method <tt>end_of_day</tt> returns a timestamp at the end of the day (23:59:59):</p>
|
2923
|
+
<div class="code_container">
|
2924
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2925
|
+
date = Date.new(2010, 6, 7)
|
2926
|
+
date.end_of_day # => Sun Jun 06 23:59:59 +0200 2010
|
2927
|
+
</pre>
|
2928
|
+
</div>
|
2929
|
+
<p><tt>beginning_of_day</tt> is aliased to <tt>at_beginning_of_day</tt>, <tt>midnight</tt>, <tt>at_midnight</tt>.</p>
|
2930
|
+
<h6 id="ago-since">16.1.6.2 <tt>ago</tt>, <tt>since</tt></h6>
|
2931
|
+
<p>The method <tt>ago</tt> receives a number of seconds as argument and returns a timestamp those many seconds ago from midnight:</p>
|
2932
|
+
<div class="code_container">
|
2933
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2934
|
+
date = Date.current # => Fri, 11 Jun 2010
|
2935
|
+
date.ago(1) # => Thu, 10 Jun 2010 23:59:59 EDT -04:00
|
2936
|
+
</pre>
|
2937
|
+
</div>
|
2938
|
+
<p>Similarly, <tt>since</tt> moves forward:</p>
|
2939
|
+
<div class="code_container">
|
2940
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2941
|
+
date = Date.current # => Fri, 11 Jun 2010
|
2942
|
+
date.since(1) # => Fri, 11 Jun 2010 00:00:01 EDT -04:00
|
2943
|
+
</pre>
|
2944
|
+
</div>
|
2945
|
+
<h5 id="other-time-computations">16.1.7 Other Time Computations</h5>
|
2946
|
+
<h4 id="date-conversions">16.2 Conversions</h4>
|
2947
|
+
<h3 id="extensions-to-datetime">17 Extensions to <tt>DateTime</tt></h3>
|
2948
|
+
<div class="warning"><p><tt>DateTime</tt> is not aware of <span class="caps">DST</span> rules and so some of these methods have edge cases when a <span class="caps">DST</span> change is going on. For example <tt>seconds_since_midnight</tt> might not return the real amount in such a day.</p></div>
|
2949
|
+
<h4 id="calculations-datetime">17.1 Calculations</h4>
|
2950
|
+
<div class="note"><p>All the following methods are defined in <tt>active_support/core_ext/date_time/calculations.rb</tt>.</p></div>
|
2951
|
+
<p>The class <tt>DateTime</tt> is a subclass of <tt>Date</tt> so by loading <tt>active_support/core_ext/date/calculations.rb</tt> you inherit these methods and their aliases, except that they will always return datetimes:</p>
|
2952
|
+
<div class="code_container">
|
2953
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2954
|
+
yesterday
|
2955
|
+
tomorrow
|
2956
|
+
beginning_of_week (monday, at_beginning_of_week)
|
2957
|
+
end_on_week (at_end_of_week)
|
2958
|
+
weeks_ago
|
2959
|
+
prev_week
|
2960
|
+
next_week
|
2961
|
+
months_ago
|
2962
|
+
months_since
|
2963
|
+
beginning_of_month (at_beginning_of_month)
|
2964
|
+
end_of_month (at_end_of_month)
|
2965
|
+
prev_month
|
2966
|
+
next_month
|
2967
|
+
beginning_of_quarter (at_beginning_of_quarter)
|
2968
|
+
end_of_quarter (at_end_of_quarter)
|
2969
|
+
beginning_of_year (at_beginning_of_year)
|
2970
|
+
end_of_year (at_end_of_year)
|
2971
|
+
years_ago
|
2972
|
+
years_since
|
2973
|
+
prev_year
|
2974
|
+
next_year
|
2975
|
+
</pre>
|
2976
|
+
</div>
|
2977
|
+
<p>The following methods are reimplemented so you do <strong>not</strong> need to load <tt>active_support/core_ext/date/calculations.rb</tt> for these ones:</p>
|
2978
|
+
<div class="code_container">
|
2979
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2980
|
+
beginning_of_day (midnight, at_midnight, at_beginning_of_day)
|
2981
|
+
end_of_day
|
2982
|
+
ago
|
2983
|
+
since (in)
|
2984
|
+
</pre>
|
2985
|
+
</div>
|
2986
|
+
<p>On the other hand, <tt>advance</tt> and <tt>change</tt> are also defined and support more options, they are documented below.</p>
|
2987
|
+
<h5 id="named-datetimes">17.1.1 Named Datetimes</h5>
|
2988
|
+
<h6 id="datetime-current">17.1.1.1 <tt>DateTime.current</tt></h6>
|
2989
|
+
<p>Active Support defines <tt>DateTime.current</tt> to be like <tt>Time.now.to_datetime</tt>, except that it honors the user time zone, if defined. It also defines <tt>DateTime.yesterday</tt> and <tt>DateTime.tomorrow</tt>, and the instance predicates <tt>past?</tt>, and <tt>future?</tt> relative to <tt>DateTime.current</tt>.</p>
|
2990
|
+
<h5 id="other-extensions">17.1.2 Other Extensions</h5>
|
2991
|
+
<h6 id="seconds_since_midnight">17.1.2.1 <tt>seconds_since_midnight</tt></h6>
|
2992
|
+
<p>The method <tt>seconds_since_midnight</tt> returns the number of seconds since midnight:</p>
|
2993
|
+
<div class="code_container">
|
2994
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
2995
|
+
now = DateTime.current # => Mon, 07 Jun 2010 20:26:36 +0000
|
2996
|
+
now.seconds_since_midnight # => 73596
|
2997
|
+
</pre>
|
2998
|
+
</div>
|
2999
|
+
<h6 id="utc-datetime">17.1.2.2 <tt>utc</tt></h6>
|
3000
|
+
<p>The method <tt>utc</tt> gives you the same datetime in the receiver expressed in <span class="caps">UTC</span>.</p>
|
3001
|
+
<div class="code_container">
|
3002
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3003
|
+
now = DateTime.current # => Mon, 07 Jun 2010 19:27:52 -0400
|
3004
|
+
now.utc # => Mon, 07 Jun 2010 23:27:52 +0000
|
3005
|
+
</pre>
|
3006
|
+
</div>
|
3007
|
+
<p>This method is also aliased as <tt>getutc</tt>.</p>
|
3008
|
+
<h6 id="utc">17.1.2.3 <tt>utc?</tt></h6>
|
3009
|
+
<p>The predicate <tt>utc?</tt> says whether the receiver has <span class="caps">UTC</span> as its time zone:</p>
|
3010
|
+
<div class="code_container">
|
3011
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3012
|
+
now = DateTime.now # => Mon, 07 Jun 2010 19:30:47 -0400
|
3013
|
+
now.utc? # => false
|
3014
|
+
now.utc.utc? # => true
|
3015
|
+
</pre>
|
3016
|
+
</div>
|
3017
|
+
<h6 id="datetime-advance">17.1.2.4 <tt>advance</tt></h6>
|
3018
|
+
<p>The most generic way to jump to another datetime is <tt>advance</tt>. This method receives a hash with keys <tt>:years</tt>, <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>, <tt>:minutes</tt>, and <tt>:seconds</tt>, and returns a datetime advanced as much as the present keys indicate.</p>
|
3019
|
+
<div class="code_container">
|
3020
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3021
|
+
d = DateTime.current
|
3022
|
+
# => Thu, 05 Aug 2010 11:33:31 +0000
|
3023
|
+
d.advance(:years => 1, :months => 1, :days => 1, :hours => 1, :minutes => 1, :seconds => 1)
|
3024
|
+
# => Tue, 06 Sep 2011 12:34:32 +0000
|
3025
|
+
</pre>
|
3026
|
+
</div>
|
3027
|
+
<p>This method first computes the destination date passing <tt>:years</tt>, <tt>:months</tt>, <tt>:weeks</tt>, and <tt>:days</tt> to <tt>Date#advance</tt> documented above. After that, it adjusts the time calling <tt>since</tt> with the number of seconds to advance. This order is relevant, a different ordering would give different datetimes in some edge-cases. The example in <tt>Date#advance</tt> applies, and we can extend it to show order relevance related to the time bits.</p>
|
3028
|
+
<p>If we first move the date bits (that have also a relative order of processing, as documented before), and then the time bits we get for example the following computation:</p>
|
3029
|
+
<div class="code_container">
|
3030
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3031
|
+
d = DateTime.new(2010, 2, 28, 23, 59, 59)
|
3032
|
+
# => Sun, 28 Feb 2010 23:59:59 +0000
|
3033
|
+
d.advance(:months => 1, :seconds => 1)
|
3034
|
+
# => Mon, 29 Mar 2010 00:00:00 +0000
|
3035
|
+
</pre>
|
3036
|
+
</div>
|
3037
|
+
<p>but if we computed them the other way around, the result would be different:</p>
|
3038
|
+
<div class="code_container">
|
3039
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3040
|
+
d.advance(:seconds => 1).advance(:months => 1)
|
3041
|
+
# => Thu, 01 Apr 2010 00:00:00 +0000
|
3042
|
+
</pre>
|
3043
|
+
</div>
|
3044
|
+
<div class="warning"><p>Since <tt>DateTime</tt> is not <span class="caps">DST</span>-aware you can end up in a non-existing point in time with no warning or error telling you so.</p></div>
|
3045
|
+
<h5 id="datetime-changing-components">17.1.3 Changing Components</h5>
|
3046
|
+
<p>The method <tt>change</tt> allows you to get a new datetime which is the same as the receiver except for the given options, which may include <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:min</tt>, <tt>:sec</tt>, <tt>:offset</tt>, <tt>:start</tt>:</p>
|
3047
|
+
<div class="code_container">
|
3048
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3049
|
+
now = DateTime.current
|
3050
|
+
# => Tue, 08 Jun 2010 01:56:22 +0000
|
3051
|
+
now.change(:year => 2011, :offset => Rational(-6, 24))
|
3052
|
+
# => Wed, 08 Jun 2011 01:56:22 -0600
|
3053
|
+
</pre>
|
3054
|
+
</div>
|
3055
|
+
<p>If hours are zeroed, then minutes and seconds are too (unless they have given values):</p>
|
3056
|
+
<div class="code_container">
|
3057
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3058
|
+
now.change(:hour => 0)
|
3059
|
+
# => Tue, 08 Jun 2010 00:00:00 +0000
|
3060
|
+
</pre>
|
3061
|
+
</div>
|
3062
|
+
<p>Similarly, if minutes are zeroed, then seconds are too (unless it has given a value):</p>
|
3063
|
+
<div class="code_container">
|
3064
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3065
|
+
now.change(:min => 0)
|
3066
|
+
# => Tue, 08 Jun 2010 01:00:00 +0000
|
3067
|
+
</pre>
|
3068
|
+
</div>
|
3069
|
+
<p>This method is not tolerant to non-existing dates, if the change is invalid <tt>ArgumentError</tt> is raised:</p>
|
3070
|
+
<div class="code_container">
|
3071
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3072
|
+
DateTime.current.change(:month => 2, :day => 30)
|
3073
|
+
# => ArgumentError: invalid date
|
3074
|
+
</pre>
|
3075
|
+
</div>
|
3076
|
+
<h5 id="datetime-durations">17.1.4 Durations</h5>
|
3077
|
+
<p>Durations can be added to and subtracted from datetimes:</p>
|
3078
|
+
<div class="code_container">
|
3079
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3080
|
+
now = DateTime.current
|
3081
|
+
# => Mon, 09 Aug 2010 23:15:17 +0000
|
3082
|
+
now + 1.year
|
3083
|
+
# => Tue, 09 Aug 2011 23:15:17 +0000
|
3084
|
+
now - 1.week
|
3085
|
+
# => Mon, 02 Aug 2010 23:15:17 +0000
|
3086
|
+
</pre>
|
3087
|
+
</div>
|
3088
|
+
<p>They translate to calls to <tt>since</tt> or <tt>advance</tt>. For example here we get the correct jump in the calendar reform:</p>
|
3089
|
+
<div class="code_container">
|
3090
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3091
|
+
DateTime.new(1582, 10, 4, 23) + 1.hour
|
3092
|
+
# => Fri, 15 Oct 1582 00:00:00 +0000
|
3093
|
+
</pre>
|
3094
|
+
</div>
|
3095
|
+
<h3 id="extensions-to-time">18 Extensions to <tt>Time</tt></h3>
|
3096
|
+
<h4 id="time-calculations">18.1 Calculations</h4>
|
3097
|
+
<div class="note"><p>All the following methods are defined in <tt>active_support/core_ext/time/calculations.rb</tt>.</p></div>
|
3098
|
+
<p>Active Support adds to <tt>Time</tt> many of the methods available for <tt>DateTime</tt>:</p>
|
3099
|
+
<div class="code_container">
|
3100
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3101
|
+
past?
|
3102
|
+
today?
|
3103
|
+
future?
|
3104
|
+
yesterday
|
3105
|
+
tomorrow
|
3106
|
+
seconds_since_midnight
|
3107
|
+
change
|
3108
|
+
advance
|
3109
|
+
ago
|
3110
|
+
since (in)
|
3111
|
+
beginning_of_day (midnight, at_midnight, at_beginning_of_day)
|
3112
|
+
end_of_day
|
3113
|
+
beginning_of_week (monday, at_beginning_of_week)
|
3114
|
+
end_on_week (at_end_of_week)
|
3115
|
+
weeks_ago
|
3116
|
+
prev_week
|
3117
|
+
next_week
|
3118
|
+
months_ago
|
3119
|
+
months_since
|
3120
|
+
beginning_of_month (at_beginning_of_month)
|
3121
|
+
end_of_month (at_end_of_month)
|
3122
|
+
prev_month
|
3123
|
+
next_month
|
3124
|
+
beginning_of_quarter (at_beginning_of_quarter)
|
3125
|
+
end_of_quarter (at_end_of_quarter)
|
3126
|
+
beginning_of_year (at_beginning_of_year)
|
3127
|
+
end_of_year (at_end_of_year)
|
3128
|
+
years_ago
|
3129
|
+
years_since
|
3130
|
+
prev_year
|
3131
|
+
next_year
|
3132
|
+
</pre>
|
3133
|
+
</div>
|
3134
|
+
<p>They are analogous. Please refer to their documentation above and take into account the following differences:</p>
|
3135
|
+
<ul>
|
3136
|
+
<li><tt>change</tt> accepts an additional <tt>:usec</tt> option.</li>
|
3137
|
+
<li><tt>Time</tt> understands <span class="caps">DST</span>, so you get correct <span class="caps">DST</span> calculations as in</li>
|
3138
|
+
</ul>
|
3139
|
+
<div class="code_container">
|
3140
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3141
|
+
Time.zone_default
|
3142
|
+
# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
|
3143
|
+
|
3144
|
+
# In Barcelona, 2010/03/28 02:00 +0100 becomes 2010/03/28 03:00 +0200 due to DST.
|
3145
|
+
t = Time.local_time(2010, 3, 28, 1, 59, 59)
|
3146
|
+
# => Sun Mar 28 01:59:59 +0100 2010
|
3147
|
+
t.advance(:seconds => 1)
|
3148
|
+
# => Sun Mar 28 03:00:00 +0200 2010
|
3149
|
+
</pre>
|
3150
|
+
</div>
|
3151
|
+
<ul>
|
3152
|
+
<li>If <tt>since</tt> or <tt>ago</tt> jump to a time that can’t be expressed with <tt>Time</tt> a <tt>DateTime</tt> object is returned instead.</li>
|
3153
|
+
</ul>
|
3154
|
+
<h5 id="time-current">18.1.1 <tt>Time.current</tt></h5>
|
3155
|
+
<p>Active Support defines <tt>Time.current</tt> to be today in the current time zone. That’s like <tt>Time.now</tt>, except that it honors the user time zone, if defined. It also defines <tt>Time.yesterday</tt> and <tt>Time.tomorrow</tt>, and the instance predicates <tt>past?</tt>, <tt>today?</tt>, and <tt>future?</tt>, all of them relative to <tt>Time.current</tt>.</p>
|
3156
|
+
<p>When making Time comparisons using methods which honor the user time zone, make sure to use <tt>Time.current</tt> and not <tt>Time.now</tt>. There are cases where the user time zone might be in the future compared to the system time zone, which <tt>Time.today</tt> uses by default. This means <tt>Time.now</tt> may equal <tt>Time.yesterday</tt>.</p>
|
3157
|
+
<h5 id="all_day-all_week-all_month-all_quarter-and-all_year">18.1.2 <tt>all_day</tt>, <tt>all_week</tt>, <tt>all_month</tt>, <tt>all_quarter</tt> and <tt>all_year</tt></h5>
|
3158
|
+
<p>The method <tt>all_day</tt> returns a range representing the whole day of the current time.</p>
|
3159
|
+
<div class="code_container">
|
3160
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3161
|
+
now = Time.current
|
3162
|
+
# => Mon, 09 Aug 2010 23:20:05 UTC +00:00
|
3163
|
+
now.all_day
|
3164
|
+
# => Mon, 09 Aug 2010 00:00:00 UTC +00:00..Mon, 09 Aug 2010 23:59:59 UTC +00:00
|
3165
|
+
</pre>
|
3166
|
+
</div>
|
3167
|
+
<p>Analogously, <tt>all_week</tt>, <tt>all_month</tt>, <tt>all_quarter</tt> and <tt>all_year</tt> all serve the purpose of generating time ranges.</p>
|
3168
|
+
<div class="code_container">
|
3169
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3170
|
+
now = Time.current
|
3171
|
+
# => Mon, 09 Aug 2010 23:20:05 UTC +00:00
|
3172
|
+
now.all_week
|
3173
|
+
# => Mon, 09 Aug 2010 00:00:00 UTC +00:00..Sun, 15 Aug 2010 23:59:59 UTC +00:00
|
3174
|
+
now.all_month
|
3175
|
+
# => Sat, 01 Aug 2010 00:00:00 UTC +00:00..Tue, 31 Aug 2010 23:59:59 UTC +00:00
|
3176
|
+
now.all_quarter
|
3177
|
+
# => Thu, 01 Jul 2010 00:00:00 UTC +00:00..Thu, 30 Sep 2010 23:59:59 UTC +00:00
|
3178
|
+
now.all_year
|
3179
|
+
# => Fri, 01 Jan 2010 00:00:00 UTC +00:00..Fri, 31 Dec 2010 23:59:59 UTC +00:00
|
3180
|
+
</pre>
|
3181
|
+
</div>
|
3182
|
+
<h4 id="time-constructors">18.2 Time Constructors</h4>
|
3183
|
+
<p>Active Support defines <tt>Time.current</tt> to be <tt>Time.zone.now</tt> if there’s a user time zone defined, with fallback to <tt>Time.now</tt>:</p>
|
3184
|
+
<div class="code_container">
|
3185
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3186
|
+
Time.zone_default
|
3187
|
+
# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
|
3188
|
+
Time.current
|
3189
|
+
# => Fri, 06 Aug 2010 17:11:58 CEST +02:00
|
3190
|
+
</pre>
|
3191
|
+
</div>
|
3192
|
+
<p>Analogously to <tt>DateTime</tt>, the predicates <tt>past?</tt>, and <tt>future?</tt> are relative to <tt>Time.current</tt>.</p>
|
3193
|
+
<p>Use the <tt>local_time</tt> class method to create time objects honoring the user time zone:</p>
|
3194
|
+
<div class="code_container">
|
3195
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3196
|
+
Time.zone_default
|
3197
|
+
# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
|
3198
|
+
Time.local_time(2010, 8, 15)
|
3199
|
+
# => Sun Aug 15 00:00:00 +0200 2010
|
3200
|
+
</pre>
|
3201
|
+
</div>
|
3202
|
+
<p>The <tt>utc_time</tt> class method returns a time in <span class="caps">UTC</span>:</p>
|
3203
|
+
<div class="code_container">
|
3204
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3205
|
+
Time.zone_default
|
3206
|
+
# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
|
3207
|
+
Time.utc_time(2010, 8, 15)
|
3208
|
+
# => Sun Aug 15 00:00:00 UTC 2010
|
3209
|
+
</pre>
|
3210
|
+
</div>
|
3211
|
+
<p>Both <tt>local_time</tt> and <tt>utc_time</tt> accept up to seven positional arguments: year, month, day, hour, min, sec, usec. Year is mandatory, month and day default to 1, and the rest default to 0.</p>
|
3212
|
+
<p>If the time to be constructed lies beyond the range supported by <tt>Time</tt> in the runtime platform, usecs are discarded and a <tt>DateTime</tt> object is returned instead.</p>
|
3213
|
+
<h5 id="time-durations">18.2.1 Durations</h5>
|
3214
|
+
<p>Durations can be added to and subtracted from time objects:</p>
|
3215
|
+
<div class="code_container">
|
3216
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3217
|
+
now = Time.current
|
3218
|
+
# => Mon, 09 Aug 2010 23:20:05 UTC +00:00
|
3219
|
+
now + 1.year
|
3220
|
+
# => Tue, 09 Aug 2011 23:21:11 UTC +00:00
|
3221
|
+
now - 1.week
|
3222
|
+
# => Mon, 02 Aug 2010 23:21:11 UTC +00:00
|
3223
|
+
</pre>
|
3224
|
+
</div>
|
3225
|
+
<p>They translate to calls to <tt>since</tt> or <tt>advance</tt>. For example here we get the correct jump in the calendar reform:</p>
|
3226
|
+
<div class="code_container">
|
3227
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3228
|
+
Time.utc_time(1582, 10, 3) + 5.days
|
3229
|
+
# => Mon Oct 18 00:00:00 UTC 1582
|
3230
|
+
</pre>
|
3231
|
+
</div>
|
3232
|
+
<h3 id="extensions-to-process">19 Extensions to <tt>Process</tt></h3>
|
3233
|
+
<h4 id="daemon">19.1 <tt>daemon</tt></h4>
|
3234
|
+
<p>Ruby 1.9 provides <tt>Process.daemon</tt>, and Active Support defines it for previous versions. It accepts the same two arguments, whether it should chdir to the root directory (default, true), and whether it should inherit the standard file descriptors from the parent (default, false).</p>
|
3235
|
+
<h3 id="extensions-to-file">20 Extensions to <tt>File</tt></h3>
|
3236
|
+
<h4 id="atomic_write">20.1 <tt>atomic_write</tt></h4>
|
3237
|
+
<p>With the class method <tt>File.atomic_write</tt> you can write to a file in a way that will prevent any reader from seeing half-written content.</p>
|
3238
|
+
<p>The name of the file is passed as an argument, and the method yields a file handle opened for writing. Once the block is done <tt>atomic_write</tt> closes the file handle and completes its job.</p>
|
3239
|
+
<p>For example, Action Pack uses this method to write asset cache files like <tt>all.css</tt>:</p>
|
3240
|
+
<div class="code_container">
|
3241
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3242
|
+
File.atomic_write(joined_asset_path) do |cache|
|
3243
|
+
cache.write(join_asset_file_contents(asset_paths))
|
3244
|
+
end
|
3245
|
+
</pre>
|
3246
|
+
</div>
|
3247
|
+
<p>To accomplish this <tt>atomic_write</tt> creates a temporary file. That’s the file the code in the block actually writes to. On completion, the temporary file is renamed, which is an atomic operation on <span class="caps">POSIX</span> systems. If the target file exists <tt>atomic_write</tt> overwrites it and keeps owners and permissions.</p>
|
3248
|
+
<div class="warning"><p>Note you can’t append with <tt>atomic_write</tt>.</p></div>
|
3249
|
+
<p>The auxiliary file is written in a standard directory for temporary files, but you can pass a directory of your choice as second argument.</p>
|
3250
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/file/atomic.rb</tt>.</p></div>
|
3251
|
+
<h3 id="extensions-to-logger">21 Extensions to <tt>Logger</tt></h3>
|
3252
|
+
<h4 id="around_-level">21.1 <tt>around_[level]</tt></h4>
|
3253
|
+
<p>Takes two arguments, a <tt>before_message</tt> and <tt>after_message</tt> and calls the current level method on the <tt>Logger</tt> instance, passing in the <tt>before_message</tt>, then the specified message, then the <tt>after_message</tt>:</p>
|
3254
|
+
<div class="code_container">
|
3255
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3256
|
+
logger = Logger.new("log/development.log")
|
3257
|
+
logger.around_info("before", "after") { |logger| logger.info("during") }
|
3258
|
+
</pre>
|
3259
|
+
</div>
|
3260
|
+
<h4 id="silence">21.2 <tt>silence</tt></h4>
|
3261
|
+
<p>Silences every log level lesser to the specified one for the duration of the given block. Log level orders are: debug, info, error and fatal.</p>
|
3262
|
+
<div class="code_container">
|
3263
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3264
|
+
logger = Logger.new("log/development.log")
|
3265
|
+
logger.silence(Logger::INFO) do
|
3266
|
+
logger.debug("In space, no one can hear you scream.")
|
3267
|
+
logger.info("Scream all you want, small mailman!")
|
3268
|
+
end
|
3269
|
+
</pre>
|
3270
|
+
</div>
|
3271
|
+
<h4 id="datetime_format">21.3 <tt>datetime_format=</tt></h4>
|
3272
|
+
<p>Modifies the datetime format output by the formatter class associated with this logger. If the formatter class does not have a <tt>datetime_format</tt> method then this is ignored.</p>
|
3273
|
+
<div class="code_container">
|
3274
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3275
|
+
class Logger::FormatWithTime < Logger::Formatter
|
3276
|
+
cattr_accessor(:datetime_format) { "%Y%m%d%H%m%S" }
|
3277
|
+
|
3278
|
+
def self.call(severity, timestamp, progname, msg)
|
3279
|
+
"#{timestamp.strftime(datetime_format)} -- #{String === msg ? msg : msg.inspect}\n"
|
3280
|
+
end
|
3281
|
+
end
|
3282
|
+
|
3283
|
+
logger = Logger.new("log/development.log")
|
3284
|
+
logger.formatter = Logger::FormatWithTime
|
3285
|
+
logger.info("<- is the current time")
|
3286
|
+
</pre>
|
3287
|
+
</div>
|
3288
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/logger.rb</tt>.</p></div>
|
3289
|
+
<h3 id="extensions-to-nameerror">22 Extensions to <tt>NameError</tt></h3>
|
3290
|
+
<p>Active Support adds <tt>missing_name?</tt> to <tt>NameError</tt>, which tests whether the exception was raised because of the name passed as argument.</p>
|
3291
|
+
<p>The name may be given as a symbol or string. A symbol is tested against the bare constant name, a string is against the fully-qualified constant name.</p>
|
3292
|
+
<div class="info"><p>A symbol can represent a fully-qualified constant name as in <tt>:"ActiveRecord::Base"</tt>, so the behavior for symbols is defined for convenience, not because it has to be that way technically.</p></div>
|
3293
|
+
<p>For example, when an action of <tt>PostsController</tt> is called Rails tries optimistically to use <tt>PostsHelper</tt>. It is OK that the helper module does not exist, so if an exception for that constant name is raised it should be silenced. But it could be the case that <tt>posts_helper.rb</tt> raises a <tt>NameError</tt> due to an actual unknown constant. That should be reraised. The method <tt>missing_name?</tt> provides a way to distinguish both cases:</p>
|
3294
|
+
<div class="code_container">
|
3295
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3296
|
+
def default_helper_module!
|
3297
|
+
module_name = name.sub(/Controller$/, '')
|
3298
|
+
module_path = module_name.underscore
|
3299
|
+
helper module_path
|
3300
|
+
rescue MissingSourceFile => e
|
3301
|
+
raise e unless e.is_missing? "#{module_path}_helper"
|
3302
|
+
rescue NameError => e
|
3303
|
+
raise e unless e.missing_name? "#{module_name}Helper"
|
3304
|
+
end
|
3305
|
+
</pre>
|
3306
|
+
</div>
|
3307
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/name_error.rb</tt>.</p></div>
|
3308
|
+
<h3 id="extensions-to-loaderror">23 Extensions to <tt>LoadError</tt></h3>
|
3309
|
+
<p>Active Support adds <tt>is_missing?</tt> to <tt>LoadError</tt>, and also assigns that class to the constant <tt>MissingSourceFile</tt> for backwards compatibility.</p>
|
3310
|
+
<p>Given a path name <tt>is_missing?</tt> tests whether the exception was raised due to that particular file (except perhaps for the “.rb” extension).</p>
|
3311
|
+
<p>For example, when an action of <tt>PostsController</tt> is called Rails tries to load <tt>posts_helper.rb</tt>, but that file may not exist. That’s fine, the helper module is not mandatory so Rails silences a load error. But it could be the case that the helper module does exist and in turn requires another library that is missing. In that case Rails must reraise the exception. The method <tt>is_missing?</tt> provides a way to distinguish both cases:</p>
|
3312
|
+
<div class="code_container">
|
3313
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
3314
|
+
def default_helper_module!
|
3315
|
+
module_name = name.sub(/Controller$/, '')
|
3316
|
+
module_path = module_name.underscore
|
3317
|
+
helper module_path
|
3318
|
+
rescue MissingSourceFile => e
|
3319
|
+
raise e unless e.is_missing? "helpers/#{module_path}_helper"
|
3320
|
+
rescue NameError => e
|
3321
|
+
raise e unless e.missing_name? "#{module_name}Helper"
|
3322
|
+
end
|
3323
|
+
</pre>
|
3324
|
+
</div>
|
3325
|
+
<div class="note"><p>Defined in <tt>active_support/core_ext/load_error.rb</tt>.</p></div>
|
3326
|
+
|
3327
|
+
<h3>Feedback</h3>
|
3328
|
+
<p>
|
3329
|
+
You're encouraged to help improve the quality of this guide.
|
3330
|
+
</p>
|
3331
|
+
<p>
|
3332
|
+
If you see any typos or factual errors you are confident to
|
3333
|
+
patch, please clone <a href="https://github.com/lifo/docrails">docrails</a>
|
3334
|
+
and push the change yourself. That branch of Rails has public write access.
|
3335
|
+
Commits are still reviewed, but that happens after you've submitted your
|
3336
|
+
contribution. <a href="https://github.com/lifo/docrails">docrails</a> is
|
3337
|
+
cross-merged with master periodically.
|
3338
|
+
</p>
|
3339
|
+
<p>
|
3340
|
+
You may also find incomplete content, or stuff that is not up to date.
|
3341
|
+
Please do add any missing documentation for master. Check the
|
3342
|
+
<a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
|
3343
|
+
for style and conventions.
|
3344
|
+
</p>
|
3345
|
+
<p>
|
3346
|
+
If for whatever reason you spot something to fix but cannot patch it yourself, please
|
3347
|
+
<a href="https://github.com/rails/rails/issues">open an issue</a>.
|
3348
|
+
</p>
|
3349
|
+
<p>And last but not least, any kind of discussion regarding Ruby on Rails
|
3350
|
+
documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
|
3351
|
+
</p>
|
3352
|
+
</div>
|
3353
|
+
</div>
|
3354
|
+
</div>
|
3355
|
+
|
3356
|
+
<hr class="hide" />
|
3357
|
+
<div id="footer">
|
3358
|
+
<div class="wrapper">
|
3359
|
+
<p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p>
|
3360
|
+
<p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
|
3361
|
+
</div>
|
3362
|
+
</div>
|
3363
|
+
|
3364
|
+
<script type="text/javascript" src="javascripts/guides.js"></script>
|
3365
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
|
3366
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
|
3367
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
|
3368
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
|
3369
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
|
3370
|
+
<script type="text/javascript">
|
3371
|
+
SyntaxHighlighter.all()
|
3372
|
+
</script>
|
3373
|
+
</body>
|
3374
|
+
</html>
|