<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>MacAdie Web Blog</title>
	<atom:link href="http://www.MacAdie.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.MacAdie.net</link>
	<description>Notes on Ruby and Java: Until The Moon Turns Red and The Screens Turn Blue</description>
	<lastBuildDate>Mon, 20 Feb 2012 18:41:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Pickaxe Book Chapter 05</title>
		<link>http://www.MacAdie.net/2012/02/20/pickaxe-book-chapter-05/</link>
		<comments>http://www.MacAdie.net/2012/02/20/pickaxe-book-chapter-05/#comments</comments>
		<pubDate>Mon, 20 Feb 2012 18:41:00 +0000</pubDate>
		<dc:creator>Eric MacAdie</dc:creator>
				<category><![CDATA[Pickaxe Book]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.MacAdie.net/?p=910</guid>
		<description><![CDATA[This chapter is about inheritance, modules and mixins. To make a subclass: class Child &#60; Parent end You can invoke parent class methods with &#8220;super&#8221;, just like in Java. You will usually want to call &#8220;super&#8221; in the initialize method if you are inheriting. On page 95, it would be nice if the &#8220;private&#8221; keyword [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F02%2F20%2Fpickaxe-book-chapter-05%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F02%2F20%2Fpickaxe-book-chapter-05%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>This chapter is about inheritance, modules and mixins.</p>
<p>To make a subclass:</p>
<pre class="brush: ruby; gutter: true">class Child &lt; Parent
end</pre>
<p>You can invoke parent class methods with &#8220;super&#8221;, just like in Java. You will usually want to call &#8220;super&#8221; in the initialize method if you are inheriting.</p>
<p>On page 95, it would be nice if the &#8220;private&#8221; keyword was tabbed in a few spaces.</p>
<p>Modules provide namespaces and allow some reusability. But unlike packages in Java it seems like they are similar to Ruby classes with two differences:<br />
1. They have the word &#8220;module&#8221; in front of the name instead of the word &#8220;class&#8221;<br />
2. Methods defined in the module have the module name in front of them. So if a Trigonometry class had a method &#8220;sin(x)&#8221; tyou would see this:</p>
<pre class="brush: ruby; gutter: true">class Trigonometry
    # This is a constant
    PI = 22/7
    def sin(x)
        # implementation
    end
    # other stuff
end</pre>
<p>A module would do it like this:</p>
<pre class="brush: ruby; gutter: true">module Trigonometry
    def Trigonometry.sin(x)
        # implementation
    end
    # other stuff
end</pre>
<p>If you use a module constant, you need to specify the module name and use the double-colon operator:</p>
<pre class="brush: ruby; gutter: true">y = Trigonometry.sin(Trigonometry::PI/2)</pre>
<p>Modules cannot have instances, so I guess they are like static classes in Java.</p>
<p>Is there inheritance for modules? I may find out</p>
<p>A mixin is when you include a module in a class. Then you can call the module&#8217;s method from a class instance as if they were parent methods.</p>
<p>The book talks quite a bit about the Enumerable mixin. I guess all you have to do is provide an &#8220;each&#8221; method, and you get all the iteration methods in collections (Array and Hash).</p>
<p>At the end of the chapter, they recommend designing programs with composition (has-a) and delegation (uses-a) instead of inheritance (is-a). They seem to say that mixins are more of a composition technique than an inheritance technique.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.MacAdie.net/2012/02/20/pickaxe-book-chapter-05/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Code Academy Week 6 Notes</title>
		<link>http://www.MacAdie.net/2012/02/18/code-academy-week-6-notes/</link>
		<comments>http://www.MacAdie.net/2012/02/18/code-academy-week-6-notes/#comments</comments>
		<pubDate>Sun, 19 Feb 2012 02:08:10 +0000</pubDate>
		<dc:creator>Eric MacAdie</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.MacAdie.net/?p=907</guid>
		<description><![CDATA[2012-02-14_08.04.44 product has many reviews There is a proxy for the data &#8211; it is a subclass of Array @review = Review.new @review.product = Product.find(params[:product_id]) What is there is no product with that ID? The &#8220;find&#8221; method will raise an exception (actually params[:product_id] is nil) How to make it more forgiving if params[:product_id].present?     @review.product [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F02%2F18%2Fcode-academy-week-6-notes%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F02%2F18%2Fcode-academy-week-6-notes%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>2012-02-14_08.04.44<br />
product has many reviews<br />
There is a proxy for the data &#8211; it is a subclass of Array</p>
<pre class="brush: ruby; gutter: true">@review = Review.new
@review.product = Product.find(params[:product_id])</pre>
<p>What is there is no product with that ID?<br />
The &#8220;find&#8221; method will raise an exception (actually params[:product_id] is nil)<br />
How to make it more forgiving</p>
<pre class="brush: ruby; gutter: true">if params[:product_id].present?
    @review.product = Product.find_by_id(params[:product_id])
end</pre>
<p>the find_by_* methods (aka dynamic finders) are more forgiving<br />
You could even get rid of if</p>
<p>How to hide the product pull down in the review form?<br />
Hidden form field<br />
In _form.html.erb for review:</p>
<pre class="brush: rails; gutter: true">&lt;% if @review.product.present? %&gt;
    &lt;%= f.hidden_field :product_id %&gt;
&lt;% else %&gt;
&lt;div&gt;
    &lt;%= f.collection_select :product_id, Product.all, :id, :name %&gt;
&lt;/div&gt;
&lt;% end %&gt;</pre>
<p>Why do we need an equal sign for if it&#8217;s a hidden field?</p>
<pre class="brush: rails; gutter: true">&lt;%= f.hidden_field :product_id %&gt;</pre>
<p>It still needs to be emitted to the HTML<br />
In Rails, we have 2 methods: present? and blank?<br />
blank? is like nil?<br />
if a string is &#8220;  &#8220;, that is not nil, but it is blank<br />
present? is the opposite of blank?<br />
Why have both? Just negate one of them.<br />
!a.blank? is &#8220;not the Ruby way&#8221; according to Jeff</p>
<pre class="brush: ruby; gutter: true">[1,2,4].map{ |n| n*2 } is just like [1,2,4].collect{ |n| n*2 }</pre>
<p>Matz does not like minimal interface. Sometimes map will feel right, and sometimes collect will.</p>
<pre class="brush: ruby; gutter: true">[1,3,5].each do |n|
    puts n
end</pre>
<p>map is an iterator, like each</p>
<pre class="brush: ruby; gutter: true">w = [1,3,5].map do |n|
    n * 2
end</pre>
<p>map wants a return value from each iteration of the block</p>
<p>&lt;% if @review.product.present? %&gt;<br />
could also be<br />
&lt;% if @review.product %&gt;</p>
<p>show.html.erb for reviews has this at the top:</p>
<pre class="brush: rails; gutter: true">&lt;%= notice %&gt;</pre>
<p>This method will emit what ever is in the :notice key in the redirect from your controller<br />
This will only live long enough to be redirected<br />
This is called a flash message in Rails<br />
it is a hash<br />
the &#8220;flash hash&#8221;<br />
You could also set the notice just before the redirect_to</p>
<pre class="brush: rails; gutter: true">flash[:notice] = &quot;Way to go!&quot;</pre>
<p>You could make it flash[:zebra]<br />
and call</p>
<pre class="brush: rails; gutter: true">&lt;%= flash[:zebra] %&gt;</pre>
<p>in the html.erb file</p>
<p>http is stateless, so each request has to provide all the information the next request needs<br />
Putting the query string in the URL has been one way to keep information<br />
User story:<br />
as a user, I want to add several products into a shopping cart<br />
Jeff does it:<br />
Carts and Products<br />
This is many to many<br />
But many carts will want to have products<br />
Make a join model in between<br />
CartItem<br />
Cart has_many :cartItems<br />
cart_item belongs_to a single :cart<br />
A product will have many cart items<br />
a cart item will belong_to a product<br />
cart_itme will have cart_id and product_id</p>
<pre class="brush: text; gutter: true">rails generate model Cart name:string
rails generate model CartItem cart_id:integer product_id:integer quantity:integer
rake db:migrate</pre>
<pre class="brush: ruby; gutter: true">class Cart
    has_many :cart_items
end</pre>
<pre class="brush: ruby; gutter: true">class CartItem
    belongs_to :cart
    belongs_to :product
end</pre>
<p>add has_many :cart_item to product<br />
The file name is Pascal case. In code or console, you use underscores</p>
<p>Jeff says the modelling is the hard part of Rails<br />
In the console, you can do this:</p>
<pre class="brush: text; gutter: true">cart = Cart.new
cart.cart_items
item = CartItem.new</pre>
<p>in console, this will reload items from database<br />
cart.cart_items(true)<br />
or: cart.cart_items.create :product =&gt; Product.last<br />
cart.cart_items.build will make a new cart in memory only.<br />
cart.cart_items.new does not exist on the proxy</p>
<p>Add item to a cart. How to add another item to same cart?<br />
Use cookies<br />
Session data<br />
Each has a name and a value<br />
name/value pair, like a hash in Ruby<br />
Expiration is optional &#8211; session by default<br />
cookie data lives in the browser<br />
How to add cookies:</p>
<pre class="brush: ruby; gutter: true">session[:name] = value</pre>
<p>Each cookie is limited to 4K of data<br />
Do not put an ActiveRecord object into a cookie<br />
Cookies are stored on the client machine<br />
deal with session hash in your controllers<br />
It is defined in ApplicationController&#8217;s parent<br />
session[:cart_id] = cart.id<br />
The session data is encrypted<br />
In the create method for Cart controller:</p>
<pre class="brush: ruby; gutter: true">if session[:cart_id]
    cart = Cart.find(session[:cart_id])
else
    cart = Cart.create
end</pre>
<p>Put the cart stuff in a partial that everything can see.<br />
app/views/share/_cart.html.erb</p>
<pre class="brush: rails; gutter: true">&lt;%= render &#039;shared/cart &gt;</pre>
<p>Instead of accessing session hash inside view, make a helper method<br />
Use view helpers</p>
<p>Seed file<br />
Pagination<br />
Seed file will help you pull in test data</p>
<p>Vince did pagination</p>
<p>Checkout: cart becomes an order<br />
Cart partial:</p>
<pre class="brush: rails; gutter: true">&lt;%= button_to &quot;Check out&quot;, orders_url %&gt;</pre>
<p>In routes:<br />
resources for <img src='http://www.MacAdie.net/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rders<br />
Create an orders controller</p>
<pre class="brush: ruby; gutter: true">def create
    # do stuff
    # now clear session data
    reset_session
    redirect_to products_url, :notice =&gt; &quot;Thanks for your order&quot;
end</pre>
<p>Look at guides for sessions and cookies</p>
<p>2012-02-16_08.20.30<br />
In grandma example, they used a form_tag, not a form_for since they did not use a model.<br />
form_tag(&#8220;/ask&#8221;, :method =&gt; &#8220;get&#8221;) do<br />
put form tags here</p>
<p>routes:<br />
get &#8216;ask&#8217; =&gt; &#8216;grandmas#ask&#8217;</p>
<p>What we started:</p>
<pre class="brush: ruby; gutter: true">input = &quot;&quot;
output = &quot;&quot;
puts &quot;Talk to grandma&quot;
while input != &quot;BYE&quot;
    input gets.chomp
    puts &quot;What?&quot;
    if input == input.uppercase
        puts &quot;No, not since #{rand(1930..1950)}&quot;
    end
end</pre>
<p>Jeff recommends irb or rails console</p>
<p>Two methods:<br />
a.upcase will check if the string contained in a is uppercase<br />
a.upcase! will change the string to uppercase</p>
<p>Some people used regular expressions</p>
<p>Now going back to the shopping cart.<br />
New models: Order, OrderItem</p>
<p>reset_session will reset the whole session<br />
how to just get rid of cart?</p>
<pre class="brush: ruby; gutter: true">session[:cart_id] = nil</pre>
<p>Cycle through the cart creating order items, and call order.save afterwards. Fewer transactions.</p>
<p>New app for users</p>
<pre class="brush: text; gutter: true">rails g model Item name:string value:integer
rails g model User name:string email:string password:string</pre>
<p>Do not store passwords as strings. We will go over that later.</p>
<p>You could put this in the seeds.rb:</p>
<pre class="brush: ruby; gutter: true">Item.create :name =&gt; &quot;Hockey Stick&quot;, :value =&gt; 100</pre>
<p>etc, etc, etc,</p>
<pre class="brush: text; gutter: true">rake db:seed</pre>
<p>To wipe out existing items in database, you could add this at the top of seeds.rb<br />
Item.destroy_all<br />
He added users and items to routes with resources</p>
<pre class="brush: text; gutter: true">rails g controller Items new create show
rails g controller users new create show</pre>
<p>Signup is easy: Just add user to database<br />
Signin and signout are session management<br />
If they are in database, when they sign in just make a session cookie</p>
<p>We create a sessions controller, inherits from application controller</p>
<pre class="brush: ruby; gutter: true">SessionsController
    def new
    end
    
    def create
    user = User.find_by_name(params[:name])
        if user.present?
            if user.password == params[:password]
                session[:user_id] = user.id
                redirect_to items_url, :notice =&gt; &quot;hello&quot;
            else
                redirect_to items_url, :notice =&gt; &quot;Nope&quot;
            end
        else
            redirect_to items_url, :notice =&gt; &quot;Nope&quot;
        end
    end
    
    def destroy
        # reset_session
        # Or
        session[:user_id] = nil
        redirect_to items_url
    end
end</pre>
<p>There will also be a folder for sessions, with a new.html.erb<br />
We use form_tag instead of form_for since we have no model</p>
<pre class="brush: rails; gutter: true">&lt;%= form_tag &quot;/sessions&quot; %&gt; (or sessions_url)
    &lt;% label_tag :name  %&gt; &lt;%= text_field :name  %&gt;
    &lt;% label_tag :password  %&gt; &lt;%= text_field :password %&gt;
    &lt;% submit_tag &#039;Sign In&#039;, new_session_url %&gt;
&lt;% end %&gt;</pre>
<p>Now in app layout:<br />
if session[:user_id].present?<br />
Hello, User.find(session[:user_id]).name</p>
<p>In routes:<br />
post &#8220;/logout&#8221; =&gt; &#8216;sessions#destroy&#8217;, :as =&gt; :logout<br />
link_to &#8220;Sign Out&#8221;,<br />
button_to will create a post</p>
<p>Make the password a password_field_tag<br />
To do password confirmation:<br />
add a text field in form: password_confirmation, which you can do even though we are in a form_for<br />
Then in model for User:<br />
validates :password, :confirmation =&gt; true</p>
<p>For password security:<br />
add &#8220;bcrypt-ruby&#8221; to Gemfile, run &#8220;bundle install&#8221;<br />
To user, add a column called &#8220;password_digest&#8221; as a string<br />
add line &#8220;has_secure_password&#8221; to the model</p>
<pre class="brush: text; gutter: true">rails g scaffold User name:string email:string favorite_color:string password_digest:string
rake db:migrate</pre>
<p>If you make a mistake,</p>
<pre class="brush: text; gutter: true">rake db:migrate rollback STEP=1</pre>
<p>Put line &#8220;has_secure_password&#8221; into the model<br />
For user form partial:<br />
Remove the password digest field from the form<br />
Put in password and password_confirmation</p>
<p>Create an account and sign in at the same time<br />
In users controller in create</p>
<pre class="brush: ruby; gutter: true">if @user.save
    session[:user_id] = @user.id
end</pre>
<p>So how do people sign in? We don&#8217;t want them to know their digest<br />
In console:</p>
<pre class="brush: ruby; gutter: true">u = User.find_by_name(&quot;Joe&quot;)
u.authenticate(&quot;hockey&quot;)</pre>
<p>That should work<br />
It will encrypt the input, it will not decrypt the string in the database</p>
]]></content:encoded>
			<wfw:commentRss>http://www.MacAdie.net/2012/02/18/code-academy-week-6-notes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Code Academy Week 5 Notes</title>
		<link>http://www.MacAdie.net/2012/02/18/code-academy-week-5-notes/</link>
		<comments>http://www.MacAdie.net/2012/02/18/code-academy-week-5-notes/#comments</comments>
		<pubDate>Sat, 18 Feb 2012 23:35:23 +0000</pubDate>
		<dc:creator>Eric MacAdie</dc:creator>
				<category><![CDATA[CA Notes]]></category>

		<guid isPermaLink="false">http://www.MacAdie.net/?p=902</guid>
		<description><![CDATA[2012-02-07_08.32.40 He went over SQL in Ruby/Rails Team has many players, Player belongs to Team User story: As a user, I want to see a list of products I can buy A product has a name, color, and price. A product belongs to a single brand. Prices are always in exact dollar amounts (no cents). [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F02%2F18%2Fcode-academy-week-5-notes%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F02%2F18%2Fcode-academy-week-5-notes%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>2012-02-07_08.32.40<br />
He went over SQL in Ruby/Rails<br />
Team has many players, Player belongs to Team</p>
<p>User story:<br />
As a user, I want to see a list of products I can buy<br />
A product has a name, color, and price. A product belongs to a single brand.<br />
Prices are always in exact dollar amounts (no cents).<br />
As a user, I want to add a review to a product<br />
A review has a rating from 1-5 and a brief description</p>
<p>new rails app<br />
products and brands<br />
products belong to brand, brand has many products<br />
Generate scaffold for brand and product<br />
go back to index after create</p>
<p>Go over the scaffold<br />
To get the brand in the collection select<br />
Go to the form partial for the product<br />
Only change the number field, not the label field<br />
brand_id is the foreign key</p>
<pre class="brush: rails; gutter: true">&lt;%= f.collection_select :brand_id, Brand.all, :id, :name %&gt;</pre>
<p>:id is param for Brand.all, :name is the field in the brand. That is what will be displayed<br />
You may not want to always do Brand.all. We will go over that later.<br />
View should not decide what data to show.<br />
Put a variable in the new method in the controller</p>
<p>Now listing the products, we still get the brand ID</p>
<p>Make the description for a form a text field, not string</p>
<pre class="brush: rails; gutter: true">f.collection_select :product_id, Product.all, :id, :name</pre>
<p>For rating, we want a list of  to 5</p>
<pre class="brush: rails; gutter: true">f.select :rating, [1,2,3,4,5]</pre>
<p>You should still add a validates method in the model<br />
What if you want 1 to 100?<br />
There is a way to do a range</p>
<pre class="brush: ruby; gutter: true">:rating, (1..100).to_a</pre>
<p>to_a converts it to an array<br />
Make the description box smaller. Go to the form partial<br />
:rows =&gt; 5</p>
<p>Gems:<br />
You can have more than one version</p>
<pre class="brush: text; gutter: true">gem install rails</pre>
<p>You may see:</p>
<pre class="brush: text; gutter: true">sudo gem install rails</pre>
<p>That will install it with admin rights<br />
With rvm: never use sudo<br />
It will install latest by default<br />
gem will handle dependencies<br />
railties is the guts/engines of rails<br />
You can call<br />
gem sources<br />
to see where it will look for gems</p>
<p>Vince&#8217;s app:<br />
We could edit the Gemfile</p>
<pre class="brush: rails; gutter: true">gem &#039;gmaps4rails&#039;</pre>
<p>Then run</p>
<pre class="brush: text; gutter: true">bundle install</pre>
<p>Back to Jeff<br />
How to get words to appear on pull-down<br />
Numbers:</p>
<pre class="brush: rails; gutter: true">f.select:rating, (1..5).to_a</pre>
<p>Or</p>
<pre class="brush: rails; gutter: true">f.select:rating, [1,2,3,4,5]</pre>
<p>or</p>
<pre class="brush: rails; gutter: true">f.select :rating, {&quot;Excellent&quot; =&gt; 5, &quot;Very Good&quot; =&gt; 4, &quot;Okay&quot; =&gt; 3, &quot;Not so good&quot; =&gt; 2, &quot;Bad&quot; =&gt; 1}</pre>
<p>To validate that the rating will be between 1 and 5<br />
Jeff starts with the guides<br />
Jeff used</p>
<pre class="brush: rails; gutter: true">validates :rating, :numericality =&gt; { <img src='http://www.MacAdie.net/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> nly_integer =&gt; true }
validates :rating, :numericality =&gt; { <img src='http://www.MacAdie.net/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> nly_integer =&gt; true, :greater_than_or_equal_to =&gt; 1, :less_than_or_equal_to =&gt; 5 }</pre>
<p>Test in the Rails console</p>
<p>2012-02-09_08.25.05<br />
To support 1 URL: pages/social<br />
One way:</p>
<pre class="brush: text; gutter: true">rails g controller pages social</pre>
<p>rails new friendBC<br />
cd friendBC</p>
<p>-&gt; Memorize the routes for resources<br />
in routes.rb<br />
get &#8220;pages/social&#8221;<br />
in app/controllers add a controller: PagesController &lt; ApplicationController<br />
add a method called &#8220;social&#8221;<br />
add app/views/pages/social.html.erb<br />
get an image, put it in</p>
<pre class="brush: sql; gutter: true">&lt;% image_tag &quot;logo.png&quot; %&gt;</pre>
<p>in assets/global directory<br />
Make the background grey<br />
app/assets/stylesheets/application.css</p>
<p>How to get JSON data?<br />
He put some stuff in his controller</p>
<pre class="brush: ruby; gutter: true">require &#039;open-uri&#039; and require &#039;json&#039;
result = JSON.parse(open(&quot;Some URL&quot;).read)</pre>
<p>Put result in view file<br />
In hashes, symbols and strings are not interchangeable. Usually they are.<br />
To get the image:<br />
in the view:</p>
<pre class="brush: rails; gutter: true">&lt;%= image_tag @first_result[&quot;video&quot;][&quot;thumbnailUrl&quot;] =&gt;
 &lt;img src=&quot;@first_result[&quot;video&quot;][&quot;thumbnailUrl&quot;]&quot;&gt;</pre>
<p>Now he is calling @result @channel<br />
&#8211;<br />
Now Jeff is going through it<br />
Agile practices: single responsibility, clear intention, DRY<br />
These are the top 3<br />
Rails cries out to help you do those things<br />
When you download someone else&#8217;s code, you may need to run &#8220;bundle install&#8221;<br />
Jeff moved some of the HTML onto a partial<br />
Then change the variable in partial to one called &#8220;channel&#8221;<br />
Then in the view call</p>
<pre class="brush: rails; gutter: true">&lt;% render &#039;ribbon&#039;, :channel =&gt; @Whatever %&gt;</pre>
<p>In the partial, do not use raw &#8220;a&#8221; and &#8220;img&#8221; tags</p>
<pre class="brush: rails; gutter: true">&lt;% link_to &quot;Video goes here&quot;, &quot;http://www.youtube.com#{post[&quot;video][&quot;hostId&quot;]}&quot; %&gt;</pre>
<p>Now add the image:</p>
<pre class="brush: rails; gutter: true">&lt;% link_to image_tag(post[&quot;video][&quot;thunmbnailUrl&quot;], :size =&gt; &quot;240x180&quot;), &quot;http://www.youtube.com#{post[&quot;video][&quot;hostId&quot;]}&quot;, :target =&gt; :blank %&gt;</pre>
<p>Now back in view, we call the render three times. What if we pull another channel, we will have to add another line.<br />
So in controller, create an array</p>
<pre class="brush: rails; gutter: true">@channels = [@facebook, @twitter, @youtube]</pre>
<p>In the view:</p>
<pre class="brush: rails; gutter: true">&lt;% @channels.each do |channel_data| %&gt;
    &lt;%= render &#039;ribbon&#039;, :channel =&gt; channel_data %&gt;
&lt;% end %&gt;</pre>
<p>Now they do not need to be instance variables in the controller<br />
We still have repetition</p>
<pre class="brush: ruby; gutter: true">def get_json_for_source(source)
    return JSON.parse((open(&quot;https://&quot;)).read)
end</pre>
<p>Then in other method:</p>
<pre class="brush: ruby; gutter: true">facebook = get_json_for_source(&#039;FACEBOOK&#039;)</pre>
<p>This is Ruby skillz</p>
<p>A good pattern to know:<br />
An array of strings. You are transforming the array into another array.</p>
<pre class="brush: ruby; gutter: true">@channels = [&#039;a&#039;, &#039;b&#039;, &#039;c&#039;].map do |source|
    get_json_for_source(source)
end</pre>
<p>map is like each<br />
Look it up<br />
collect is another good one to look up.</p>
<pre class="brush: ruby; gutter: true">@names = users.collect dp |user|
    user.name
end</pre>
<p>Could be</p>
<pre class="brush: ruby; gutter: true">@names = users.collect {|user| user.name}</pre>
<p>We saw one-line blocks in scaffolds in index</p>
<pre class="brush: ruby; gutter: true">respond_to do |format|
    format.json {render json: @brands}
end
format.json do
    render json: @brands
end</pre>
<p>Look in the dev/tth/shop folder<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;<br />
Now: git and github<br />
Look up &#8220;git &#8211; the simple guide&#8221;</p>
<pre class="brush: text; gutter: true">git init</pre>
<p>makes a new repository</p>
<pre class="brush: text; gutter: true">git clone /path/to</pre>
<p>to checkout a repository<br />
Workflow:<br />
working dir has files, index to stage commits, the head is the last commit<br />
adding and committing</p>
<pre class="brush: text; gutter: true">git add &lt;filename&gt;
 git add *
 git commit -m &quot;message&quot;</pre>
<p>Now it is in the head, but not remote</p>
<pre class="brush: text; gutter: true">git push origin master</pre>
<p>afterwards, you can just do git push<br />
To add a branch</p>
<pre class="brush: text; gutter: true">git remote add origin &lt;server&gt;
 git checkout -b feature_x
 git pull to update - that pulls down latest changes</pre>
<p>to reset:</p>
<pre class="brush: text; gutter: true">git fetch origin; git reset --hard origin/master</pre>
<p>gitk &#8211; is a good GUI<br />
Neal making live changes</p>
<pre class="brush: text; gutter: true">git status</pre>
<p>He is on master branch</p>
<pre class="brush: text; gutter: true">git branch</pre>
<p>git status now tells him he made a change</p>
<pre class="brush: text; gutter: true">git add .
 git commit -am &quot;updated the Readme&quot;
 git push origin master</pre>
<p>or just</p>
<pre class="brush: text; gutter: true">git push</pre>
<p>There is also heroku</p>
<pre class="brush: text; gutter: true">git push heroku master</pre>
<p>or</p>
<pre class="brush: text; gutter: true">git push heroku</pre>
<p>Heroku requires postgres</p>
<p>Neal makes a new app</p>
<pre class="brush: text; gutter: true">rails new ca_boat_party</pre>
<p>It would be nice to stop an existing rails server<br />
You could also specify a port</p>
<pre class="brush: text; gutter: true">rails s -p 4000</pre>
<p>It is now live on our local machine</p>
<pre class="brush: text; gutter: true">git init</pre>
<p>go to github.com<br />
make a new repository</p>
<pre class="brush: text; gutter: true">ca_boat_party - same name as directory
 git add .
 git commit -am &quot;&quot;</pre>
<p>No good</p>
<pre class="brush: text; gutter: true">git remote add origin git@github.com:nealg223/ca_boat_party
 git push -u origin master</pre>
<p>Now put it up to heroku</p>
<pre class="brush: text; gutter: true">gem install heroku</pre>
<p>ssh keys are a pain</p>
<pre class="brush: text; gutter: true">heroku create ca-boat-party --stack cedar</pre>
<p>They have different stacks. bamboo is the current stack, good for rails up to 3.0. For rails 3.1 use cedar<br />
Now push it to heroku<br />
Update the gem file Gemfile to add postgres</p>
<pre class="brush: ruby; gutter: true">group :production do
     gem &#039;pg&#039;
 end</pre>
<p>Put sqlite3 in group :development<br />
bundle install<br />
now commit changes to git</p>
<pre class="brush: text; gutter: true">git add
 git commit -am &quot;changed Gemfile&quot;
 git push</pre>
<p>Now push to heroku</p>
<pre class="brush: text; gutter: true">git push heroku master</pre>
<p>another command: heroku open<br />
assets, like images, there could be some problems<br />
another command is heroku logs<br />
or</p>
<pre class="brush: text; gutter: true">  heroku run console</pre>
<p>it&#8217;s like an irb for heroku</p>
<pre class="brush: text; gutter: true">heroku run rake db:migrate</pre>
<p>in file app/config/environments/production.rb</p>
<pre class="brush: ruby; gutter: true">set config.assets.compile = true</pre>
<p>You can go to gitref.org<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;<br />
Working with Shop app:<br />
Get the average of reviews for a product</p>
<pre class="brush: ruby; gutter: true">p = Product.find(1)
 p.reviews</pre>
<p>Calling product.reviews: It gets rows from our table. It looks like an array, and behave like an array, but it can do more than what an array can do. It returns a proxy class. It is a proxy for the data you want.<br />
So you can say p.reviews.count &#8211; it makes an SQL statement<br />
You can do a lot of array stuff: p.reviews.first, p.reviews.sum(&#8220;rating&#8221;)<br />
Arrays do not have sum method, but ActiveRecord does have sum method<br />
p.reviews.average(&#8220;rating&#8221;) it gives us a BigDecimal instance<br />
p.reviews.average(&#8220;rating&#8221;).to_s</p>
<p>Another association concept<br />
A brand has many products.<br />
A product has many reviews.<br />
A brand has many products throught its products.</p>
<pre class="brush: ruby; gutter: true">class Brand &lt; ActiveRecord::Base
     has_many :products
     has_many :reviews, :through =&gt; :products
 end</pre>
<p>The lines must be in that order<br />
Review does not have brand id, but product has brand id, and review has product ID<br />
So you can just do Brand.reviews without looping<br />
Users want to see average rating for brand<br />
So in brand show page &#8211; put it there for each brand<br />
So to brand index page:</p>
<pre class="brush: rails; gutter: true">&lt;%= brand.name %&gt;</pre>
<p>Rating:</p>
<pre class="brush: rails; gutter: true">&lt;%= brand.reviews.average(:rating) %&gt;</pre>
<p>For reviewing the product form, it would be great if it knew which product you were using<br />
No params hash for /reviews/new<br />
Put a placeholder in the route<br />
Put it in URL via ?key=value<br />
Now you have a params hash<br />
In product/show.html.erb</p>
<pre class="brush: rails; gutter: true">&lt;%= link_to &quot;Review This Product&quot;, new_review_url(:product_id =&gt; @product.id) %&gt;</pre>
<p>So now you see ?product_id=1 in url for new form<br />
so in controller, look at new action in review controller</p>
<pre class="brush: ruby; gutter: true">def new
     @review = Review.new
     @review.product_id = params[:product_id]
     # or @review.product = Product.find(params[:product_id])
     respond_to
 end</pre>
<p>so in reviews/new.html.erb<br />
New review for</p>
<pre class="brush: rails; gutter: true">&lt;%= @review.product.name %&gt;</pre>
<p>Next: Leave out the pull-down form. But get product ID<br />
replace collection_select with a hidden field</p>
]]></content:encoded>
			<wfw:commentRss>http://www.MacAdie.net/2012/02/18/code-academy-week-5-notes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Notes On Coupling</title>
		<link>http://www.MacAdie.net/2012/02/13/notes-on-coupling/</link>
		<comments>http://www.MacAdie.net/2012/02/13/notes-on-coupling/#comments</comments>
		<pubDate>Tue, 14 Feb 2012 03:12:50 +0000</pubDate>
		<dc:creator>Eric MacAdie</dc:creator>
				<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://www.MacAdie.net/?p=899</guid>
		<description><![CDATA[I found some notes I took in 2004 at a lecture I attended on coupling. It may have been a lecture Dave Thomas gave at CJUG. Decoupling your code: coupling: you can change something, and something else changes too Methods calling methods: hard to understand, hard to maintain, hard to re-use. Symptoms: Minor change recompiles [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F02%2F13%2Fnotes-on-coupling%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F02%2F13%2Fnotes-on-coupling%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>I found some notes I took in 2004 at a lecture I attended on coupling. It may have been a lecture Dave Thomas gave at CJUG.</p>
<p>Decoupling your code:<br />
coupling: you can change something, and something else changes too<br />
Methods calling methods: hard to understand, hard to maintain, hard to re-use.</p>
<p>Symptoms: Minor change recompiles the whole system. Unit tests require every jar on the box. Things stop working when you change their context. Hard to partition project between subteams.</p>
<p>Treat code like spy cells: limit interactions, if one is broken all others are safe, enforced structure.</p>
<p>Some coupling is good. Some code must call other code. Make it deliberate.</p>
<p>Types of coupling: Static, dynamic, domain, temporal.</p>
<p>Static coupling:<br />
Classes are staticly coupled if one needs another to compile.<br />
Java has interfaces. Good to couple to something more abstract. Gang of Four says to program to interfaces.<br />
Interfaces reduce coupling. Split intent from implementation, single point of abstraction. Interfaces != list of class&#8217;s methods.<br />
Inheritance is also static coupling. What if parent class changes?<br />
Different rules for inheritance. Java: easy to inherit, hard to delegate. Inheritance is okay for &#8220;is-a&#8221;, bad for &#8220;has-a&#8221; or &#8220;uses-a&#8221;. Business world &#8211; not many uses for &#8220;is-a&#8221;, more &#8220;has-a&#8221; and &#8220;uses-a&#8221;<br />
How to delegate?</p>
<p>Dynamic coupling:<br />
happens at run-time. method chaining: order.getCustomer().getAddress().getState()<br />
coupling question: what can change? What can break? Those methods can change.<br />
Start by asking what caller is doing. Express intent at point of call.<br />
Large-scale coupling: Compiling is transitive: a -&gt; b, b -&gt; c, then a -&gt; c<br />
can be circular.<br />
use observer pattern: can break circular chains. Linear chain: add a layer. Mediator class. Is that a GoF pattern?<br />
Mediator: construction manager. You deal with manager, manager deals with subcontractors. manager negotiates between subcontractors.</p>
<p>Subsystems: Things that need to be coupled tend to cluster. make each a subsystem. Ex: java package. Put a facade on a package. Security: read facade, read-write facade, returned via factories.</p>
<p>Domain coupling:<br />
Business rules in code. When rules change, code must change. Value can be parameterized. Behavior can be too. Use interpreter. Interpreter pattern. Define action codes (pick out verbs)<br />
Activate: A<br />
Upgrade: U<br />
Ship: S<br />
Referral: R</p>
<p>Add strings of action codes to database.<br />
Action code: idea from cobol. Do a search. Book idea: Cobol Principles for Java<br />
not GoF intprepter pattern. Give users a screen to link product and actions.</p>
<p>Temporal coupling:<br />
Coupling in time: dependence on sequence of events. imposing a sequence where none is needed.<br />
Recommended: first edition of Bertrand Nayer&#8217;s book<br />
Invariant: something that must be true. Invariant must be true at all times.<br />
Design for concurrency. Do stuff in parallel. use a state machine. Can use mediator pattern. Threads: hard, okay with hash maps. Processed-based: RMI, SOAP. Message-based: JMS</p>
<p>Static coupling: reduce with interfaces, facade, delegation<br />
Dynamic coupling: reduce with mediator, command pattern, express intent at point of call<br />
Domain coupling: reduce with metadata, interpreter<br />
Temporal coupling: reduce with monitor and maintain class invariants, synchronize correct places, parallelism</p>
]]></content:encoded>
			<wfw:commentRss>http://www.MacAdie.net/2012/02/13/notes-on-coupling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Code Academy Week 4 Notes</title>
		<link>http://www.MacAdie.net/2012/02/12/code-academy-week-4-notes/</link>
		<comments>http://www.MacAdie.net/2012/02/12/code-academy-week-4-notes/#comments</comments>
		<pubDate>Mon, 13 Feb 2012 04:09:07 +0000</pubDate>
		<dc:creator>Eric MacAdie</dc:creator>
				<category><![CDATA[CA Notes]]></category>

		<guid isPermaLink="false">http://www.MacAdie.net/?p=887</guid>
		<description><![CDATA[I only seem to have notes for the second day of week 4. 2012-02-02 Notes Scaffolding notes: respond_to partials: Like a server side include Look up respond_to method respond_to do &#124;format&#124;      format.html      format.json { render json: @runners } end JSON only: respond_to do &#124;format&#124;      format.json { render json: @runners } end You [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F02%2F12%2Fcode-academy-week-4-notes%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F02%2F12%2Fcode-academy-week-4-notes%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>I only seem to have notes for the second day of week 4.</p>
<p>2012-02-02 Notes</p>
<p>Scaffolding notes:<br />
respond_to<br />
partials: Like a server side include</p>
<p>Look up respond_to method</p>
<pre class="brush: ruby; gutter: true">respond_to do |format|
     format.html
     format.json { render json: @runners }
 end</pre>
<p>JSON only:</p>
<pre class="brush: ruby; gutter: true">respond_to do |format|
     format.json { render json: @runners }
 end</pre>
<p>You could use curl as well.</p>
<pre class="brush: text; gutter: true">514  curl -v &quot;http://localhost:3000/runners&quot;
 515  curl -v &quot;http://localhost:3000/runners.json&quot;
 516  curl -v &quot;http://localhost:3000/runners&quot; -H &quot;Accept: text/html&quot;
 518  curl -v &quot;http://localhost:3000/runners&quot; -H &quot;Accept: application/json&quot;</pre>
<p>Try getting a png:</p>
<pre class="brush: text; gutter: true">ca-imac1-2: ~/dev/tth/MarathonApp$ curl -v &quot;http://localhost:3000/runners&quot; -H &quot;Accept: image/png&quot;
 * About to connect() to localhost port 3000 (#0)
 *   Trying 127.0.0.1... connected
 * Connected to localhost (127.0.0.1) port 3000 (#0)
 &gt; GET /runners HTTP/1.1
 &gt; User-Agent: curl/7.21.4 (universal-apple-darwin11.0) libcurl/7.21.4 OpenSSL/0.9.8r zlib/1.2.5
 &gt; Host: localhost:3000
 &gt; Accept: image/png
 &gt;
 &lt; HTTP/1.1 406 Not Acceptable
 &lt; Content-Type: image/png; charset=utf-8
 &lt; X-Ua-Compatible: IE=Edge
 &lt; Cache-Control: no-cache
 &lt; X-Request-Id: 0e74fdad7575b392561230a70fb0cadd
 &lt; X-Runtime: 0.001522
 &lt; Content-Length: 1
 &lt; Server: WEBrick/1.3.1 (Ruby/1.9.3/2011-10-30)
 &lt; Date: Thu, 02 Feb 2012 14:42:53 GMT
 &lt; Connection: Keep-Alive
 &lt;
 * Connection #0 to host localhost left intact
 * Closing connection #0</pre>
<p>I did not know there was a code 406.</p>
<p>There is a method called responds_with :html, :json, <img src='http://www.MacAdie.net/wp-includes/images/smilies/icon_mad.gif' alt=':x' class='wp-smiley' /> ml<br />
Not used too often.  That was intended for all actions, but people did not want universal responders.</p>
<p>Scaffold does not provide any security out of the box.</p>
<p>New action also has a block to send json back<br />
526  curl -v &#8220;http://localhost:3000/runners/new.json&#8221; -H &#8220;Accept: application/json&#8221;<br />
returns</p>
<pre class="brush: text; gutter: true">{&quot;created_at&quot;:null,&quot;id&quot;:null,&quot;name&quot;:null,&quot;updated_at&quot;:null}</pre>
<p>This could help other developers know what data fields your classes have</p>
<p>The create action has an if block in the respond_to call to handle both a successful and unsuccessful creation.</p>
<p>In Ruby 1.9, you can use a new syntax for hashes</p>
<pre class="brush: ruby; gutter: true">h = {:color =&gt; “Blue”, “fruit” =&gt; “apple”}</pre>
<p>You could also do it like JSON</p>
<pre class="brush: ruby; gutter: true">i = {color: “Blue”, “fruit” =&gt; “apple”}</pre>
<p>You can only use the colon for keys if your key is a symbol.<br />
So if you mix key types like in hash i, things get a bit ocnfusing. Your value can be a symbol, but that colon must still be on the left.</p>
<p>Assigment: look at the destroy. What is head :no_content about?</p>
<p>Memorize the RESTful Design chart with the routes, URLs, actions, etc</p>
<p>Let’s look at new and edit<br />
TextMate tip: could go to the drawer. There is another way to get there. Command-T pops up a window, type in the name of your file. You can type something in the middle.<br />
Look at the “new.html.erb” page. Where is the form?<br />
Look at the “edit.html.erb” page. Where is the form?<br />
We see this in each file:</p>
<pre class="brush: rails; gutter: true">&lt;%= render &#039;form&#039; %&gt;</pre>
<p>There is a file app/views/runners/_form.html.erb<br />
Partials begin with underscores.<br />
You just use the render method.<br />
You can use instance variables in the partial.</p>
<p>From index.html, you could take this and put it in a partial:</p>
<pre class="brush: rails; gutter: true">&lt;% @runners.each do |runner| %&gt;
     &lt;tr&gt;
     &lt;td&gt;&lt;%= runner.name %&gt;&lt;/td&gt;
     &lt;td&gt;&lt;%= link_to &#039;Show&#039;, runner %&gt;&lt;/td&gt;
     &lt;td&gt;&lt;%= link_to &#039;Edit&#039;, edit_runner_path(runner) %&gt;&lt;/td&gt;
     &lt;td&gt;&lt;%= link_to &#039;Destroy&#039;, runner, confirm: &#039;Are you sure?&#039;, method: :delete %&gt;&lt;/td&gt;
     &lt;/tr&gt;
 &lt;% end %&gt;</pre>
<p>into a file called _list_of_runners.html.erb<br />
and replace it with</p>
<pre class="brush: rails; gutter: true">&lt;% render ‘list_of_runners’ %&gt;</pre>
<p>It makes the index.html clearer, but clutters up the directory.</p>
<p>Back to associations:<br />
One-to-Many<br />
One movie has many actors:</p>
<pre class="brush: ruby; gutter: true">class Movie &lt; ActiveRecord::Base
     has_many :actors
 end</pre>
<pre class="brush: ruby; gutter: true">class Actor &lt; ActiveRecord::Base
     belongs_to :movie
 end</pre>
<p>User stories:<br />
As a user, I want to see the list of teams in our softball league.<br />
A team has a company name and a nickname.<br />
As a user, I want to select a team, and see the list of players on the team.<br />
A player has a name and a jersey number.</p>
<p>What about many-to-many?<br />
Actors are in many movies, and movies have many actors.<br />
There is the notion of a “Role” in between Movie and Actor. That joins them together.<br />
Movie &lt;-&gt; Role &lt;-&gt; Actor<br />
Movie has many roles, and an Actor can have many roles<br />
Roles would have id, movie_id and actor_id</p>
<pre class="brush: ruby; gutter: true">class Actor &lt; ActiveRecord::Base
     has_many :roles
 end</pre>
<pre class="brush: ruby; gutter: true">class Role &lt; ActiveRecord::Base</pre>
<p dir="ltr">    belongs_to :movie</p>
<p dir="ltr">    belongs_to :actor<br />
end</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>User &lt;-&gt; Review &lt;-&gt; Landmark</p>
<p>You just generate a model for a role<br />
rails g scaffold Movie title:string year:integer<br />
rails g scaffold Actor name:string<br />
rails g model role movie_id: integer actor_id:integer character:string<br />
Add the has_many and belongs_to statements</p>
<p>IN the console:<br />
the hard way</p>
<pre class="brush: ruby; gutter: true">Role.create :movie_id =&gt; 1, :actor_id =&gt; 1, :character_name =&gt;’Lucky Day’
 amigos.roles
 r = amigos.roles.first
 r.movie
 r.actor
 r.actor.name</pre>
<p>Another way to create a role</p>
<pre class="brush: ruby; gutter: true">amigos.roles
 amigos.roles.create :actor_id =&gt; 2, :character =&gt; ‘Dusty Bottoms’
 mark = Actor.create :name =&gt; ‘Mark Hamill’
 star_wars.roles.create :actor =&gt; mark
 starwars.roles.create :actor =&gt; Actor.find_by_id(3), :name =&gt; “Leia”</pre>
<p>Some stuff on migrations and controller filters<br />
What about the salary for the role?<br />
You cannot put it in the old migration file and re-run that<br />
The timestamps are on there for a reason</p>
<p>You need to create a new migration for the new field<br />
rails generate migration $NAME $FIELD:$TYPE<br />
rails generate migration AddSalaryToRole salary:integer<br />
It might generate the right thing. You would need this:</p>
<pre class="brush: ruby; gutter: true">def change
     add_column :roles, :salary, :integer
 end</pre>
<p>Then type rake db:migrate to make changes<br />
rake db:version</p>
<p>Controller filters:<br />
In the controller, we do</p>
<pre class="brush: ruby; gutter: true">@movie Movie.find(params[:id])</pre>
<p>quite a few times. (This would be better for something that is multiple lines.)<br />
Make a method<br />
def find_the_movie<br />
It might generate the right thing.<br />
end<br />
You can call that when you need to<br />
But there is still some repetition<br />
If you want to call a method at the beginning of an action or method, that is a before filter<br />
Put this at the top:</p>
<pre class="brush: ruby; gutter: true">before_filter :find_the_movie</pre>
<p>So even though destroy action has @movie in the first line, you won’t get an error since you get @movie from the filter<br />
But index method does not get params[:id]. You will get an error<br />
So how to run it only for certain actions</p>
<pre class="brush: ruby; gutter: true">before_filter :find_the_movie, <img src='http://www.MacAdie.net/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> nly =&gt; [:show, :edit, :update, :destroy]</pre>
<p>or to exclude some methods</p>
<pre class="brush: ruby; gutter: true">before_filter :find_the_movie, :except =&gt; [:index, :new, :create]</pre>
<p>DRY-ing code:<br />
partials in views, pull them in with renders<br />
controllers: use filters to extract common code</p>
<p>You can make your db lookups faster with indexes:</p>
<pre class="brush: ruby; gutter: true">add_index :roles, :movie_id</pre>
<p>You can put these in a migration<br />
You probably want this for foreign keys</p>
]]></content:encoded>
			<wfw:commentRss>http://www.MacAdie.net/2012/02/12/code-academy-week-4-notes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pickaxe Book Chapter 04</title>
		<link>http://www.MacAdie.net/2012/02/09/pickaxe-book-chapter-04/</link>
		<comments>http://www.MacAdie.net/2012/02/09/pickaxe-book-chapter-04/#comments</comments>
		<pubDate>Fri, 10 Feb 2012 05:41:10 +0000</pubDate>
		<dc:creator>Eric MacAdie</dc:creator>
				<category><![CDATA[Pickaxe Book]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.MacAdie.net/?p=885</guid>
		<description><![CDATA[This chapter starts out with arrays (square brackets) and hashes (curly braces), which are important to know. It says that blocks when combined with collections are good iterators. The elements in arrays and hashes can be any type. Using different methods, arrays can be different data structures: sets, queues, dequeues, FIFO queues, instead of using [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F02%2F09%2Fpickaxe-book-chapter-04%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F02%2F09%2Fpickaxe-book-chapter-04%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>This chapter starts out with arrays (square brackets) and hashes (curly braces), which are important to know. It says that blocks when combined with collections are good iterators. The elements in arrays and hashes can be any type. Using different methods, arrays can be different data structures: sets, queues, dequeues, FIFO queues, instead of using different classes. In Ruby hashes, it keeps the objects in the order they were entered. Keep the names of the block parameters unique. You could use a colon, but I think it is better to keep them unique.</p>
<p>A block can be empty:</p>
<pre class="brush: ruby; gutter: true">def three_times
    puts &quot;in method three_times&quot;
    yield
    yield
    yield
    puts &quot;leaving three_times&quot;
end

three_times { }
# { puts &quot;Hello&quot; }</pre>
<p>But you must put in a block if a method has &#8220;yield&#8221; in it, even if yield has a parameter</p>
<p>To keep track of how many times you have gone through the loop, instead of each, use each_with_index. You will need a second variable for the block: index to track the count.</p>
<pre class="brush: ruby; gutter: true">f = File.open(&quot;para.txt&quot;)
f.each_with_index do |line,index|
    puts &quot;Line #{index} is: #{line}&quot;
f.close</pre>
<p>I did not quite get the &#8220;inject&#8221; method, and I skipped over some of the stuff about enumerators since it said I could.<br />
Class methods start with the word &#8220;self&#8221; in front of them</p>
<p>At the end it gets into using blocks for closures and lambdas. Do we get into that with Rails? I think I get this stuff, but sometimes I have to look at it for a few minutes to get it. I don&#8217;t think I really know too well. Plus it appears there is another syntax for Ruby 1.9, which makes it more confusing.</p>
<p>There is an encouraging note at the end that if you don&#8217;t get it now, it&#8217;s okay. Thanks, Dave!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.MacAdie.net/2012/02/09/pickaxe-book-chapter-04/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Code Academy Week 4</title>
		<link>http://www.MacAdie.net/2012/02/08/code-academy-week-4/</link>
		<comments>http://www.MacAdie.net/2012/02/08/code-academy-week-4/#comments</comments>
		<pubDate>Wed, 08 Feb 2012 22:27:26 +0000</pubDate>
		<dc:creator>Eric MacAdie</dc:creator>
				<category><![CDATA[Code Academy]]></category>

		<guid isPermaLink="false">http://www.MacAdie.net/?p=881</guid>
		<description><![CDATA[I really do not have too much to say right now about week 4. I really want to post something, even if it&#8217;s really short, just to stay consistent. We learn about many-to-many associations this week.]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F02%2F08%2Fcode-academy-week-4%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F02%2F08%2Fcode-academy-week-4%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>I really do not have too much to say right now about week 4. I really want to post something, even if it&#8217;s really short, just to stay consistent.</p>
<p>We learn about many-to-many associations this week.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.MacAdie.net/2012/02/08/code-academy-week-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pickaxe Book Chapter 03</title>
		<link>http://www.MacAdie.net/2012/02/08/pickaxe-book-chapter-03/</link>
		<comments>http://www.MacAdie.net/2012/02/08/pickaxe-book-chapter-03/#comments</comments>
		<pubDate>Wed, 08 Feb 2012 22:25:36 +0000</pubDate>
		<dc:creator>Eric MacAdie</dc:creator>
				<category><![CDATA[Pickaxe Book]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.MacAdie.net/?p=879</guid>
		<description><![CDATA[This chapter was pretty easy. Mostly about objects and variables. So what is an attribute? It seems like it is another name for an instance variable. They start with an &#8220;at&#8221; symbol. I am still not too clear what a symbol is. I did not pay too much attention to the part on protected methods. [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F02%2F08%2Fpickaxe-book-chapter-03%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F02%2F08%2Fpickaxe-book-chapter-03%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>This chapter was pretty easy. Mostly about objects and variables.</p>
<p>So what is an attribute? It seems like it is another name for an instance variable. They start with an &#8220;at&#8221; symbol. I am still not too clear what a symbol is.</p>
<p>I did not pay too much attention to the part on protected methods. I read somewhere that Bjarne Stroustrup, the creator of C++, at one point said the &#8220;protected&#8221; keyword was a mistake. Ever since then I have not paid much attention to protected.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.MacAdie.net/2012/02/08/pickaxe-book-chapter-03/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pickaxe Book Chapter 02</title>
		<link>http://www.MacAdie.net/2012/01/30/pickaxe-book-chapter-002/</link>
		<comments>http://www.MacAdie.net/2012/01/30/pickaxe-book-chapter-002/#comments</comments>
		<pubDate>Mon, 30 Jan 2012 21:52:42 +0000</pubDate>
		<dc:creator>Eric MacAdie</dc:creator>
				<category><![CDATA[Pickaxe Book]]></category>

		<guid isPermaLink="false">http://www.MacAdie.net/?p=873</guid>
		<description><![CDATA[Here are some notes on Chapter 2 of the Pickaxe book. &#160; Single quoted strings take less processing, no interpolation Return value of a method is the last statement, so you may not always want/need to put a &#8220;return&#8221; statement in there. Local variables, method parameters and method names all start with lower case or [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F01%2F30%2Fpickaxe-book-chapter-002%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F01%2F30%2Fpickaxe-book-chapter-002%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Here are some notes on Chapter 2 of the Pickaxe book.</p>
<p>&nbsp;</p>
<p>Single quoted strings take less processing, no interpolation<br />
Return value of a method is the last statement, so you may not always want/need to put a &#8220;return&#8221; statement in there.<br />
Local variables, method parameters and method names all start with lower case or underscore.<br />
Global variables start with a dollar sign.<br />
Instance variables start with an at symbol.<br />
Class variables start with two at symbols.<br />
Class names, module names and constants start with uppercase letter.<br />
Character after @ may not be a digit<br />
Multi-word instance variables get underscores between words, multiword class names get camel case.<br />
Method names may end with ?, ! and =, although these have special meaning.</p>
<p>Arrays: like lists or arrays in Java, unlike primitive arrays you do not need to specify the size ahead of time.<br />
Hashes: Like maps in Java.<br />
The values do not need to be of the same type.<br />
Shortcut for arrays:<br />
a = ['ant', 'bee', 'cat', 'dog', 'elk']<br />
same as<br />
a = %w{ant bee cat dog elk}</p>
<p>Symbols: A lot of people in class had trouble with this concept. I am not too clear on it myself. They can be used as keys for hashes.<br />
There is also a new Ruby 1.9 syntax for hashes.<br />
Here is the old way:</p>
<pre class="brush: ruby; gutter: true">inst_section = {
  :cello     = &#039;string&#039;,
  :clarinet  = &#039;woodwind&#039;,
  :violin    = &#039;string&#039;
}</pre>
<p>Now you can do this as well:</p>
<pre class="brush: ruby; gutter: true">inst_section = {
  cello:    &#039;string&#039;,
  clarinet: &#039;woodwind&#039;,
  violin:   &#039;string&#039;
}</pre>
<p>This has caused some controversy on some Ruby mailing lists.<br />
There are no braces for control structures. Instead Ruby uses the keyword &#8220;end&#8221;.<br />
Next the book covers regular expressions. I am not going to get into details here. I have seen this before, although I know there is a lot to see.<br />
Blocks are a bit weird to me. I will have to look them up somewhere. It seems to me like it is just another arg to a method. Is it special because it is code?<br />
I altered some of the code from the book to make a method take a parameter as well as a block:</p>
<pre class="brush: ruby; gutter: true">def call_block(arg)
  puts &quot;Start of method&quot;
  puts &quot;arg is #{arg}&quot;
  yield
  yield
  puts &quot;End of method&quot;
end

call_block(&#039;hello&#039;){ puts &quot;In the block&quot; }
puts &quot;About to call call_block with no block&quot;
call_block(&#039;empty block&#039;){}</pre>
<p>The book says that blocks are used to implement iterators. I can never remember how to iterate through stuff. I will have to make a separate post about that.</p>
<pre class="brush: ruby; gutter: true">cities = [&#039;Chicago&#039;, &#039;Austin&#039;, &#039;Dallas&#039; , &#039;Houston&#039;]
cities.each {|city| puts &quot;The city is #{city}&quot;}

3.upto()6 {|i| print i}
(&#039;a&#039;..&#039;e&#039;).each {|char| puts char}</pre>
<p>The I/O section talks about printf. I thought the whole point of Ruby was not to deal with C?<br />
puts prints to the terminal, gets gets from the terminal.<br />
The command like arguments are in an array called ARGV.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.MacAdie.net/2012/01/30/pickaxe-book-chapter-002/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Code Academy Week 3</title>
		<link>http://www.MacAdie.net/2012/01/30/code-academy-week-3/</link>
		<comments>http://www.MacAdie.net/2012/01/30/code-academy-week-3/#comments</comments>
		<pubDate>Mon, 30 Jan 2012 21:41:40 +0000</pubDate>
		<dc:creator>Eric MacAdie</dc:creator>
				<category><![CDATA[Code Academy]]></category>

		<guid isPermaLink="false">http://www.MacAdie.net/?p=867</guid>
		<description><![CDATA[I am a bit late, but here is my summary of week 3. The lectures were rounding out MVC. We made a model class, a controller class, and some view pages. We then made the necessary methods, views and routes to list all the instances, show one instance, edit an instance, and delete an instance. [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F01%2F30%2Fcode-academy-week-3%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.MacAdie.net%2F2012%2F01%2F30%2Fcode-academy-week-3%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<div id="attachment_868" class="wp-caption alignleft" style="width: 210px"><a href="http://www.MacAdie.net/wp-content/uploads/2012/01/ActorJamesSpader.png"><img class="size-full wp-image-868" title="ActorJamesSpader" src="http://www.MacAdie.net/wp-content/uploads/2012/01/ActorJamesSpader.png" alt="James Spader" width="200" height="325" /></a><p class="wp-caption-text">James Spader is the baddest mo-fo evah!</p></div>
<p>I am a bit late, but here is my summary of week 3.</p>
<p>The lectures were rounding out MVC. We made a model class, a controller class, and some view pages. We then made the necessary methods, views and routes to list all the instances, show one instance, edit an instance, and delete an instance. I have been planning to sit down and whip up an MVC example. I just started it last night. I will do it again tonight.</p>
<p>Then Jeff said that we don&#8217;t really need to do that. You can just run the</p>
<pre class="brush: text; gutter: true">rails generate scaffold blah blah blah</pre>
<p>command. Neal pointed out that most people never learn the long way of doing it, they just learn the short way with scaffolding.  Not even the Hartl tutorial covers the detailed way, which kind of surprises me. The ironic thing is that on one day my pair partner is a guy who was taking a semester off from getting a computer science degree from Michigan State. When we had seen the &#8220;long&#8221; way of doing MVC in Rails, we were surprised at how easy it was compared to other frameworks.</p>
<p>I also saw my mentor. I wanted to do something with OAuth. I made some progress, but I hit a wall. I think the example that I was using was a bit out of date. Uncle Bob spoke. I got there late, but I was told that I saw the meat of the lecture.</p>
<p>I think I need to start getting more disciplined. I think that the &#8220;I have seen this before&#8221; phase may be ending for me. This is one of the reasons that I am going over the Pickaxe book. Another reason is that there was a shindig hosted by Braintree. Another student said she heard someone at the event who works at one of the local consulting firms saying that Code Academy should not teach just Rails, but more Ruby, since only learning Rails might not be giving people enough knowledge. This is a second-hand (or even third-hand) account of the event. But I guess there is some skepticism about Code Academy.</p>
<p>I also told another student that he looks like James Spader, and now he probably thinks I am a total jerk.</p>
<p><em>Image of <a title="http://en.wikipedia.org/wiki/James_Spader" href="http://en.wikipedia.org/wiki/James_Spader" target="_blank">James Spader</a> taken in 2007, found on Wikipedia</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.MacAdie.net/2012/01/30/code-academy-week-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

