Flowdock

# Recent notes

July 16, 2009
0 thanks

#### Usage example

Usage example:

```cube = lambda {|x| x * x * x }
cube.call(3)  # => 27
cube.call(6)  # => 216```
July 15, 2009
0 thanks

#### Time.now in views.

Be careful if you use Time.now in views with time zone support enabled, as this will not actually do the time zone conversion.

July 14, 2009
2 thanks

#### Not for floats

You should use assert_in_delta when comparing floating-point numbers.

July 13, 2009
1 thank

#### Any base logarithm

Using basic arithmetic you can get logarithm with any base:

```def log_with_base base, num
Math.log(num) / Math.log(base)
end
```

Examples:

```>> log_with_base 2, 10
=> 3.32192809488736
>> log_with_base 2, 2
=> 1.0
>> log_with_base 2, 4
=> 2.0
>> log_with_base 2, 16
=> 4.0
>> log_with_base 4, 16
=> 2.0
```
July 13, 2009
0 thanks

#### Any base logarithm

Using basic arithmetic you can get logarithm with any base:

```def log_with_base base, num
Math.log(num) / Math.log(base)
end
```

Examples:

```>> log_with_base 2, 10
=> 3.32192809488736
>> log_with_base 2, 2
=> 1.0
>> log_with_base 2, 4
=> 2.0
>> log_with_base 2, 16
=> 4.0
>> log_with_base 4, 16
=> 2.0
```
July 8, 2009
0 thanks

#### Change Column. pt-br

Em sua migration escreva da seguinte forma:

#### Exemplo de uso.

```def self.up
change_column :sua_tabela, :seu_campo, :seu_tipo_campo
end
```
July 8, 2009
1 thank

#### Change Column.

Into your migration write the follow:

#### Using Exemple

```def self.up
change_column :yourtable, :your_field, :your_type_field
end
```
July 8, 2009
1 thank

#### This is an alias

July 8, 2009 - (<= v1_8_7_72)
5 thanks

#### Using block version in Ruby < 1.8.7

The block usage was added in 1.8.7, so to get the same functionality in an earlier version of Ruby, you need to utilize the find method.

Here is a quick example:

```match = list.find { |l| l.owner == myself }
match_index = list.index(match)
```

If you do some gymnastics, you can have it on one line without extra variables:

```match_index = list.index(list.find { |l| l.owner == myself })
```
July 7, 2009 - (<= v2.3.2)
5 thanks

#### Options

Available options are (none of these exists by default):

```* :limit - Requests a maximum column length. This is number of characters for :string and :text columns and number of bytes for :binary and :integer columns.
* :default - The column‘s default value. Use nil for NULL.
* :null - Allows or disallows NULL values in the column. This option could have been named :null_allowed.
* :precision - Specifies the precision for a :decimal column.
* :scale - Specifies the scale for a :decimal column.
```
July 7, 2009
0 thanks

#### Pretty Printing Routes

if you’d like to check out your routes in the console, you can do something like:

```routes = ActionController::Routing::Routes
```

# which will return a RouteSet puts routes.routes

which’ll give you a nice output like: GET /messages/ {:action=>“index”, :controller=>“messages”} GET /messages.:format/ {:action=>“index”, :controller=>“messages”} POST /messages/ {:action=>“create”, :controller=>“messages”} POST /messages.:format/ {:action=>“create”, :controller=>“messages”} GET /messages/new/ {:action=>“new”, :controller=>“messages”} GET /messages/new.:format/ {:action=>“new”, :controller=>“messages”} GET /messages/:id/edit/ {:action=>“edit”, :controller=>“messages”} GET /messages/:id/edit.:format/ {:action=>“edit”, :controller=>“messages”} GET /messages/:id/ {:action=>“show”, :controller=>“messages”} GET /messages/:id.:format/ {:action=>“show”, :controller=>“messages”} PUT /messages/:id/ {:action=>“update”, :controller=>“messages”} PUT /messages/:id.:format/ {:action=>“update”, :controller=>“messages”} DELETE /messages/:id/ {:action=>“destroy”, :controller=>“messages”} DELETE /messages/:id.:format/ {:action=>“destroy”, :controller=>“messages”}

July 5, 2009
2 thanks

#### To verify if the element exists before replacing.

Just add this code into a initializer file.

Atention: The code starts at the “module ActionView” and the last “end” has to be copied too.

module ActionView

```module Helpers
module PrototypeHelper
class JavaScriptGenerator #:nodoc:
module GeneratorMethods
def replace_html_if_exists(id, *options_for_render)
call "if(\$('#{id}')) Element.update", id, render(*options_for_render)
end
end
end
end
end
```

end

July 1, 2009
4 thanks

#### Example

User = Struct.new(:name, :phone)

marc = User.new(“Marc”, “555-5555”)

June 30, 2009
3 thanks

#### Be careful with name of attribute writer

```attr_accessible :foo,
```

When using these nested attributes you end up with code like

```attr_accessible :foo, :bar_attributes
```

Its very easy to leave of the _attributes suffix e.g

```attr_accessible :foo, :bar
```

which will cause you all sorts of problems

June 29, 2009
2 thanks

#### :selected

If you want some object to be selected by default, be sure to use its id, not the whole object.

``` collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:selected => current_book.authors.map(&:id)})
#=> :selected => [1,2,3,4]
```

and not

```collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:selected => current_book.authors})
```
June 25, 2009
1 thank

#### Returns a copy of the attribute contents

As szeryf notes, this is a really expensive method, but another important remark is that the contents returned are a copy of the actual values.

```model.attributes['name'] # => 'Joe'
model.attributes['name'] = 'Jim'
model.attributes['name'] # => 'Joe' still
model.name # => 'Joe'
```

This has the potential to be confusing as you’re given the impression you have direct access to the attributes.

June 25, 2009
2 thanks

#### Antonym of empty?

The antonym of empty? is Enumerable#any? method:

```[].empty?  #=> true
[].any?    #=> false
[1].empty? #=> false
[1].any?   #=> true
```

Be cautious however, if your array might contain nil’s or false’s:

```[false, nil].any? #=> false
```
June 25, 2009 - (>= v2.3.2)
1 thank

#### Validate() is run always before one of the more specific validation methods

I did not see this mentioned explicitly anywhere.

The method validate is run always before a call to validate_on_create or validate_on_update is made.

Example:

```class Foo < ActiveRecord::Base
def validate
puts 'In validate'
end

def validate_on_create
puts 'In validate_on_create'
end

def validate_on_update
puts 'In validate_on_update'
end
end
```

Now, when creating a new Foo using script/console, the output is as follows:

```In validate
In validate_on_create
```

and when updating a Foo, the output looks like:

```In validate
In validate_on_update
```
June 22, 2009
3 thanks

#### Optional local assigns

When you have a partial with optional local assigns, for instance:

```<%= render :partial => 'articles/preview' %>
<%= render :partial => 'articles/preview', :locals => { :show_call_out => true } %>
```

And you don’t want the partial to break when the local isn’t assigned, you can reference it through the local_assigns local variable instead of through the template binding:

```<% if local_assigns[:show_call_out] %>
<em><%= format @article.call_out %></em>
<% end %>```
June 19, 2009
1 thank

#### class Aa

``` class_inheritable_accessor :test
end
=> [:test]

Aa.test = 10
=> 10

Aa.test
=> 10

Bb = Class.new(Aa)
=> Bb

Bb.test
=> 10

Bb.test = 5
=> 5

Bb.test
=> 5

Aa.test
=> 10
```
June 19, 2009
2 thanks

#### Re: How to test different responses

```@request.accept = "text/javascript" #=> request JS
```

as rubymaverick and nachocab suggested, you can also pass :format when calling your action, eg:

```it "GET #most_viewed renders #most_viewed.js.rjs template if js requested" do
get :most_viewed, :format => 'js'
response.should render_template('most_viewed')
end
```
June 18, 2009
3 thanks

#### Not really deprecated

This isn’t really deprecated, it’s just relocated to ActiveRecord::AttributeMethods#read_attribute

June 18, 2009
12 thanks

#### Important note

It has been said that “it can be compared to, but isn’t the same thing as”:

```class Bar
class << self
attr_accessor :greeting
end
end
```

Which is true. However, they are “inherited” isn’t exactly the case. Rather, cattr_accessor uses class variables.

The problem with class variables in Ruby, is that a class variable is the same object across all subclasses of a class. Consider the following example of what happens with cattr_accessor:

```class A
@@foo = 'foo'

def self.foo
@@foo
end
end

p A.foo # => "foo"

class B < A
end

p B.foo # => "foo"

class B
@@foo = 'bar'
end

p B.foo # => "bar"
```

So far so good you might think. However, something you might not have expected is that the variable has now also changed in class A:

```p A.foo # => "bar"
```

This is in my opinion almost never what you’d want. More probable is that you’d want the individual class instance to have an accessor. (Remember classes are objects in Ruby). I do the following in regular Ruby:

```class A
class << self
attr_accessor :foo
end

self.foo = 'foo'
end

p A.foo # => "foo"

class B < A
end

p B.foo # => nil

class B
self.foo = 'bar'
end

p B.foo # => "bar"

p A.foo # => "foo"
```

As you can see, this returns nil when a value hasn’t explicitly been set yet on the new class instance. If you’d like to have inheritance without messing with the superclasses variables, have a look at ActiveSupport’s class_inheritable_accessor, which does the same as I just explained, but creates a clone of the object and assigns it to the subclass whenever a class is inherited.

What I’d normally do in Ruby to fix the issue of it returning nil is to create the accessor manually and have it set the instance variable to the default if it’s nil:

```class A
class << self
def foo
@foo ||= 'foo'
end
end
end

class B < A
end

p B.foo # => nil
```

So to recap:

• cattr_accessor uses class variables (@@foo), in which case the object is shared across all subclasses of a class. Use it mainly for static data, in which case you’d probably best use a constant.

• class_inheritable_accessor (or what I showed) uses instance variables (@foo) at the Class instance level. These variables are not shared across all subclasses.

June 18, 2009
3 thanks

#### Expensive method!

This method builds the a new hash every time it’s called, so be cautious not to use it in loops etc.

June 17, 2009
3 thanks

#### Skipping validation

Unlike the save method, you can’t pass false to update_attributes to tell it to skip validation. Should you wish to do this (consider carefully if this is wise) update the attributes explicitly then call save and pass false:

```@model_name.attributes = params[:model_name]
@model_name.save false
```
June 16, 2009
0 thanks

This may not be the behaviour that you want, and setting :discard_day => false doesn’t change this. One way of getting around this is to hide the month field using CSS e.g.

```#some_date_field_2i {
display:none;
}
```

If you use the :default option for the date_select, the correct default month will be passed through to the controller. Using this with :discard_year will give you a dropdown with only the day, but preserve the month and year as provided by :default.

June 13, 2009 - (>= v2.3.2)
0 thanks

#### Requirements for extra parameters not working

nm. just delete this entry

June 12, 2009
3 thanks

#### cattr_accessor_with_default

Class attribute assessors are neat if you want to set up modifiable constant-like varibles. This is how you’d normally set it up:

```module MyPlugin
class Conf
@@awesome_level = 'huge'
cattr_accessor :awesome_level
end
end
```

Then you can call and modify it like this:

```>> MyPlugin::Conf.awesome_level
=> 'huge'
>> MyPlugin::Conf.awesome_level = 'massive'
>> MyPlugin::Conf.awesome_level
=> 'massive'
```

If you have a pile of those accessors I’d do something like this (there might be a better way, but it works):

```module MyPlugin
class Conf
def self.cattr_accessor_with_default(name, value = nil)
cattr_accessor name
self.send("#{name}=", value) if value
end

cattr_accessor_with_default :awesome_level, 'huge'
cattr_accessor_with_default :speed_level, 'insane'
cattr_accessor_with_default :indifferent_level
cattr_accessor_with_default :craziness_level, 'nuts'
end
end
```

This way you declare accessor and it’s optional default value on the same line

June 12, 2009
0 thanks

#### share_examples_for “a shape” do

```   it "should have a color" do
@shape.color.should == :black
end
end

describe "a circle" do
before(:all) do
@shape = Circle.new
end
it_should_behave_like "a shape"
end
```
June 12, 2009
0 thanks

#### it “should use a dummy method with argument and return value” do

``` dummy = mock("dummy").stub!(:emulate)