Browse files

Update controller topics to 1.9-style hashes (#313)

  • Loading branch information...
1 parent 847e64f commit c6b5a621f25683ff579301a48aaa72eca02d5a7f @kytrinyx kytrinyx committed Nov 17, 2012
View
12 source/topics/controllers/filters.markdown
@@ -60,7 +60,7 @@ def wrap_actions
begin
yield
rescue
- render :text => "It broke!"
+ render text: "It broke!"
end
end
```
@@ -78,7 +78,7 @@ For example, we could remove the condition from the `before_filter` sample above
```ruby
class ArticlesController < ApplicationController
- before_filter :load_article, :only => [:show, :edit, :update, :destroy]
+ before_filter :load_article, only: [:show, :edit, :update, :destroy]
# Actions...
@@ -93,7 +93,7 @@ Or get the same effect using `:except`:
```ruby
class ArticlesController < ApplicationController
- before_filter :load_article, :except => [:index, :new, :create]
+ before_filter :load_article, except: [:index, :new, :create]
#...
```
@@ -116,7 +116,7 @@ private
end
class ArticlesController < ApplicationController
- before_filter :load_article, :only => [:show, :edit, :update, :destroy]
+ before_filter :load_article, only: [:show, :edit, :update, :destroy]
# Actions...
end
@@ -141,7 +141,7 @@ private
end
class ArticlesController < ApplicationController
- before_filter :find_resource, :only => [:show, :edit, :update, :destroy]
+ before_filter :find_resource, only: [:show, :edit, :update, :destroy]
# Actions...
end
@@ -154,7 +154,7 @@ end
1. Implement a `before_filter` in `ArticlesController` to remove all calls to `find` in the actions.
2. Implement an `after_filter` that turns the article titles to all uppercase, but does not change the data in the database.
3. Implement a `before_filter` for just the `create` action on `CommentsController` that replaces the word `"sad"` with `"happy"` in the incoming comment body.
-4. Implement an `around_filter` that catches an exception, writes an apology into the `flash[:notice]`, and redirects to the articles `index`. If the exception was raised in `articles#index`, render the message as plain text (`render :text => "xyz"`). Cause an exception and make sure it works.
+4. Implement an `around_filter` that catches an exception, writes an apology into the `flash[:notice]`, and redirects to the articles `index`. If the exception was raised in `articles#index`, render the message as plain text (`render text: "xyz"`). Cause an exception and make sure it works.
## References
View
16 source/topics/controllers/flash.markdown
@@ -71,14 +71,14 @@ class ArticlesController < ApplicationController
end
```
-We can pass a `:notice =>` argument to `redirect_to` like this:
+We can pass a `notice:` argument to `redirect_to` like this:
```ruby
class ArticlesController < ApplicationController
def destroy
article = Article.find(params[:id])
article.destroy
- redirect_to articles_path, :notice => "Article '#{article.title}' was deleted."
+ redirect_to articles_path, notice: "Article '#{article.title}' was deleted."
end
end
```
@@ -90,7 +90,7 @@ class ArticlesController < ApplicationController
def destroy
article = Article.find(params[:id])
article.destroy
- redirect_to articles_path, :flash => {:error => "Article '#{article.title}' was deleted."}
+ redirect_to articles_path, flash: {error: "Article '#{article.title}' was deleted."}
end
end
```
@@ -132,24 +132,24 @@ In Ruby, if you ask a hash for a key that doesn't exist you'll get back `nil`. S
5 lines to display one message? We can refactor it by using the `content_tag` helper and an inline condition:
```erb
-<%= content_tag :p, flash[:notice], :class => "flash notice" if flash[:notice] %>
+<%= content_tag :p, flash[:notice], class: "flash notice" if flash[:notice] %>
```
### Iterating
If our application uses multiple keys, like `:notice`, `:alert`, and `:error`, then we'd need to do that three times:
```erb
-<%= content_tag :p, flash[:notice], :class => "flash notice" if flash[:notice] %>
-<%= content_tag :p, flash[:alert], :class => "flash alert" if flash[:alert] %>
-<%= content_tag :p, flash[:error], :class => "flash error" if flash[:error] %>
+<%= content_tag :p, flash[:notice], class: "flash notice" if flash[:notice] %>
+<%= content_tag :p, flash[:alert], class: "flash alert" if flash[:alert] %>
+<%= content_tag :p, flash[:error], class: "flash error" if flash[:error] %>
```
Iteration allows us to reduce the redundancy:
```erb
<% flash.each do |key, message| %>
- <%= content_tag :p, message, :class => "flash #{key}" %>
+ <%= content_tag :p, message, class: "flash #{key}" %>
<% end %>
```
View
8 source/topics/controllers/friendly-urls.markdown
@@ -201,7 +201,7 @@ Our goal is achieved, but we have introduced a possible bug: if a name starts wi
```ruby
class Tag < ActiveRecord::Base
#...
- validates_format_of :name, :without => /^\d/
+ validates_format_of :name, without: /^\d/
def self.find(input)
input.to_i == 0 ? find_by_name(input) : super
end
@@ -246,7 +246,7 @@ The library defaults to a `String` column named `slug`. If you have that column,
```ruby
class Tag < ActiveRecord::Base
extend FriendlyId
- friendly_id :name, :use => :slugged
+ friendly_id :name, use: :slugged
end
```
@@ -255,7 +255,7 @@ end
You can see it in action here:
```irb
-> t = Tag.create(:name => "Ruby on Rails")
+> t = Tag.create(name: "Ruby on Rails")
# => #<Tag id: 16, name: "Ruby on Rails", created_at: "2011-09-11 15:42:53", updated_at: "2011-09-11 15:42:53", slug: "ruby-on-rails">
> Tag.find 16
# => #<Tag id: 16, name: "Ruby on Rails", created_at: "2011-09-11 15:42:53", updated_at: "2011-09-11 15:42:53", slug: "ruby-on-rails">
@@ -275,4 +275,4 @@ We can use `.find` with an ID or the slug transparently. When the object is conv
2. Change the `to_param` in `Article` so the output does not include the `id`
3. Try to modify the `show` action of `ArticlesController` so the lookup with work with the no-`id`-having slug from exercise 2. Why is this impossible to implement efficiently?
4. Implement FriendlyID, as described above, so tags use only their name in URLs.
-5. Implement FriendlyID so article URLs no longer use the `id`, only the article's parameterized `title`.
+5. Implement FriendlyID so article URLs no longer use the `id`, only the article's parameterized `title`.
View
4 source/topics/controllers/parameters.markdown
@@ -126,8 +126,8 @@ def create
That is equivalent, given our example `params`, to this:
```ruby
-@article = Article.new(:title => params[:article][:title],
- :body => params[:article][:body])
+@article = Article.new(title: params[:article][:title],
+ body: params[:article][:body])
```
In this long form, we're building up a hash with keys `:title` and `:body`, but it's pointless! When we query for `params[:article]` we get back the nested hash. That hash has keys `:title`, `:body` -- exactly as we're building up here. So when we use this form:
View
32 source/topics/controllers/render_and_redirect.markdown
@@ -8,7 +8,7 @@ The normal controller/view flow is to display a view template corresponding to t
## Render
-The `render` method is very overloaded in Rails. Most developers encounter it within the view template, using `render :partial => 'form'` or `render @post.comments`, but here we'll focus on usage within the controller.
+The `render` method is very overloaded in Rails. Most developers encounter it within the view template, using `render partial: 'form'` or `render @post.comments`, but here we'll focus on usage within the controller.
### `:action`
@@ -24,12 +24,12 @@ def update
if @book.update_attributes(params[:book])
redirect_to(@book)
else
- render :action => :edit
+ render action: :edit
end
end
```
-When `render :action => :edit` is executed it *only* causes the `edit.html.erb` view template to be displayed. The actual `edit` action in the controller will *not* be executed.
+When `render action: :edit` is executed it *only* causes the `edit.html.erb` view template to be displayed. The actual `edit` action in the controller will *not* be executed.
As of Rails 3, the same effect can be had by abbreviating to `render :edit`.
@@ -52,7 +52,7 @@ You can use `render` to display content directly from the controller without usi
You can render plain text with the `:text` parameter:
```ruby
-render :text => "Hello, World!"
+render text: "Hello, World!"
```
This can be useful for debugging but is otherwise rarely used.
@@ -62,8 +62,8 @@ This can be useful for debugging but is otherwise rarely used.
You can render XML or JSON version of an object:
```ruby
-render :xml => @article
-render :json => @article
+render xml: @article
+render json: @article
```
Rails will automatically call `.to_json` or `.to_xml` on the passed object for you.
@@ -73,13 +73,13 @@ Rails will automatically call `.to_json` or `.to_xml` on the passed object for y
When using `render` you can override the default layout with the `:layout` option:
```ruby
-render :show, :layout => 'top_story'
+render :show, layout: 'top_story'
```
Or, maybe in response to an AJAX request, you might want to render the view template with no layout:
```ruby
-render :show, :layout => false
+render :show, layout: false
```
## Redirect
@@ -111,7 +111,7 @@ redirect_to 'http://rubyonrails.org'
By default Rails will use the HTTP status code for "temporary redirect." If you wanted to respond with some other status code, you can add the `:status` parameter:
```ruby
-redirect_to 'http://rubyonrails.org', :status => 301
+redirect_to 'http://rubyonrails.org', status: 301
```
The request would be marked with status code 301, indicating a permanent relocation.
@@ -121,8 +121,8 @@ The request would be marked with status code 301, indicating a permanent relocat
You can set a flash message within your call to `redirect_to`. It will accept the keys `:notice` or `:alert`:
```ruby
-redirect_to articles_path, :notice => "Article Created"
-redirect_to login_path, :alert => "You must be logged in!"
+redirect_to articles_path, notice: "Article Created"
+redirect_to login_path, alert: "You must be logged in!"
```
## `redirect_to` and `render` do not `return`
@@ -134,7 +134,7 @@ Here's how that could go wrong. Imagine you have a `delete` action like this:
```ruby
def destroy
article = Article.destroy(params[:id])
- redirect_to articles_path, :notice => "Article '#{article.title}' was deleted."
+ redirect_to articles_path, notice: "Article '#{article.title}' was deleted."
end
```
@@ -144,7 +144,7 @@ Then you begin adding security to your application. You've seen "guard clauses"
def destroy
redirect_to login_path unless current_user.admin?
article = Article.destroy(params[:id])
- redirect_to articles_path, :notice => "Article '#{article.title}' was deleted."
+ redirect_to articles_path, notice: "Article '#{article.title}' was deleted."
end
```
@@ -166,9 +166,9 @@ The article gets destroyed either way. The `redirect_to` does not stop execution
def destroy
if current_user.admin?
article = Article.destroy(params[:id])
- redirect_to articles_path, :notice => "Article '#{article.title}' was deleted."
+ redirect_to articles_path, notice: "Article '#{article.title}' was deleted."
else
- redirect_to login_path, :notice => "Only admins can delete articles."
+ redirect_to login_path, notice: "Only admins can delete articles."
end
end
```
@@ -191,4 +191,4 @@ end
## Reference
-* RailsGuide on Layouts and Rendering: http://guides.rubyonrails.org/layouts_and_rendering.html
+* RailsGuide on Layouts and Rendering: http://guides.rubyonrails.org/layouts_and_rendering.html
View
4 source/topics/controllers/sessions_and_conversations.markdown
@@ -109,7 +109,7 @@ rake db:migrate
Then open `config/initializers/session_store.rb` and change the line like this:
```ruby
-MyApp::Application.config.session_store :cookie_store, :key => '_myapp_session'
+MyApp::Application.config.session_store :cookie_store, key: '_myapp_session'
```
To this:
@@ -143,7 +143,7 @@ Setup and start the Redis server. Add a dependency on the `redis-store` gem to y
Open `config/initializers/session_store.rb` and change the line like this:
```ruby
-MyApp::Application.config.session_store :cookie_store, :key => '_myapp_session'
+MyApp::Application.config.session_store :cookie_store, key: '_myapp_session'
```
To this:
View
8 source/topics/controllers/slimming_controllers.markdown
@@ -287,12 +287,12 @@ The `find_or_initialize_by` method will return the record with the given id if i
```irb
> a = Article.new
=> #<Article id: nil, title: nil, body: nil, created_at: nil, updated_at: nil>
-> a.attributes = {:title => "Hello"}
- => {:title=>"Hello"}
+> a.attributes = {title: "Hello"}
+ => {title:"Hello"}
> a.inspect
=> "#<Article id: nil, title: \"Hello\", body: nil, created_at: nil, updated_at: nil>"
-> a.attributes = {:body => "World"}
- => {:body=>"World"}
+> a.attributes = {body: "World"}
+ => {body:"World"}
> a
=> #<Article id: nil, title: "Hello", body: "World", created_at: nil, updated_at: nil>
```

0 comments on commit c6b5a62

Please sign in to comment.