Flowdock

Recent notes

RSS feed
December 12, 2011
2 thanks

Need to extend class when using this

I had to dig around to find this out - if you want to use memoize somewhere, like an ActiveRecord model, you need to add

extend ActiveSupport::Memoizable

to the class. This doesn’t seem to be explained anywhere (the only docs are 3 year old blog posts anyway).

December 8, 2011
1 thank

hidden field can be changed by JS

Plumba, it’s not that useless if you think about possibility to change a hidden field with JS

December 5, 2011
0 thanks

Not available

Actually, this method is not available now.(github.com/ruby/ruby/blob/trunk/rational.c#L2352)

December 2, 2011 - (>= v3.0.0)
0 thanks

Difference in DateTimes ...

Mostly, the database date columns are DateTime instances. Whereas Rails adds several useful utility functions to DateTime (in activesupport), there is some confusing behavior. This is at least somewhat surprising.

Two subtract two DateTime instances, you should always “round” the returned value. Suppose:

d1 = DateTime.now d2 = d1 - 5.days.ago

then, d1 - d2 is a Rational, which tells you the difference between dates only after rounding. Thus, diff_in_days = (d1 - d2).round

December 1, 2011 - (>= v3.0.0)
1 thank

This method isn't deprecated

This method was moved to AbstractController::Callbacks, as stated on [1].

It took me a while to figure out ‘what should I use instead before_filter’. Hope this helps anyone that hits the same road I’m in.

1
November 29, 2011
0 thanks

index doesn't work

@ssoroka even I’m having same issue. how did you resolve it?

November 21, 2011
0 thanks

Custom configuration keys

It is nice to know, that you can store any custom configuration key in configure block… E.g.

YourApp::Application.configure do
   # ...
   config.my_custom_setting = "QWERTY1234"
end

Then you can just access it by calling

YourApp::Application.config.my_custom_setting
November 21, 2011 - (>= v3.1.0)
0 thanks

Rails 3.1 - Use request.url instead

As request.request_uri has been deprecated, use

request.url

instead.

November 16, 2011
1 thank

Change in clone for ActiveRecord objects in ruby-1.9.3

I noticed that cloning an active record object in ruby-1.9.3 and then changing an attribute on the original object will actually change the cloned object as well. This was not the case in ruby-1.9.2.

November 16, 2011
1 thank

Alternative definition

a.flat_map(&b) works exactly like a.map(&b).flatten!(1).

November 16, 2011
0 thanks

Examples in a readable format :)

Here are the above examples in a somewhat more readable format:

# Assert a basic route: a controller with the default action (index) 
assert_routing/home’, :controller =>home’, :action =>index’
# Test a route generated with a specific controller, action, and parameter (id) 
assert_routing/entries/show/23’, :controller =>entries’, :action =>show’, :id => 23
# Assert a basic route (controller + default action), with an error message if it fails 
assert_routing/store’, 
               { :controller =>store’, :action =>index’ }, 
               {}, 
               {},Route for store index not generated properly’
# Tests a route, providing a defaults hash 
assert_routingcontroller/action/9’, 
               {:id =>9”, :item =>square”}, 
               {:controller =>controller”, :action =>action”}, 
               {}, 
               {:item =>square”}
# Tests a route with a HTTP method 
assert_routing({ :method =>put’, :path =>/product/321’ }, 
               { :controller =>product”, :action =>update”, :id =>321” })
November 15, 2011 - (v3.1.0)
0 thanks

Wrapping with select tag

I didn’t knew how to wrap the output with <select> tag. I didn’t want to use raw html, but the doc doesn’t mention another way.

So, here is what I tried and it’s working:

<%= f.select :entry, option_groups_from_collection_for_select(@categories, :entries, :name, :id, :name) %>

I hope this helps anyone. :-)

November 14, 2011 - (v3.1.0)
2 thanks

Rails

For Rails 3.1 check see:

http_basic_authenticate_with :name => "username", :password => "pass" 
November 12, 2011 - (<= v2.3.8)
0 thanks

Specify attachment names

If you want to give your attachment a name, you can do this:

attachment :filename => 'my_file.txt', :body => File.read('/var/null')

It will appear to the recipient as a file named “my_file.txt” rather than something awful like “noname 1”.

November 11, 2011
3 thanks

Catching and throwing -- don't!

@wiseleyb and @glosakti, neither of your suggestions are necessary, and both are bad practices.

This test:

test "transactions" do
  assert_raises ZeroDivisionError do
    User.transaction do
      1/0
    end
  end
end

passes just fine on its own, with the transaction rolled back as you’d expect. No need to hack something ugly together.

November 10, 2011
0 thanks

logic in class/id

If you need to place some simple logic in class or like that, I think that best to make it with simple brackets:

Code example

<%= link_to ‘All actions’, switch_action_tab_path, :remote => true, :class => (‘selected’ if @tab == ‘all’) %>

November 7, 2011 - (<= v3.0.9)
1 thank

unscoped.all / unscoped.count

At least in console, doing unscoped.all or unscoped.count initially returns expected results but, after you’ve added new records outside of the default_scope those two calls seem to use some cached values.

Therefore it should always be used with the block (as they sort of imply in the doc). unscoped { all } and unscoped {count }

November 6, 2011 - (>= v3.1.0)
3 thanks

Removed in 3.1.x

This method (and #auto_link_urls) has been removed in Rails 3.1 - other options are out there, such as Rinku, however there is a gem you can use for migration purposes etc, which is rails_autolink: http://rubygems.org/gems/rails_autolink

October 26, 2011
2 thanks

Adding to the URL

If you want to use polymorphic routing for your object but you also need to specify other stuff like an anchor, you can explicitly generate the polymorphic url with extra options:

form_for @candidate,
  :url => polymorphic_path(@candidate, :anchor => 'signup')
October 19, 2011 - (>= v3.0.0)
3 thanks

Replaced by :on => :create

From rails 3,

before_validation_on_create 

has been removed and replaced with:

before_validation :foo, :on => :create
October 18, 2011
0 thanks

Upgrading to 3.x

http://railscasts.com/episodes/202-active-record-queries-in-rails-3

Since this is deprecated, one can watch the Railcast for upgrading to 3.x

The equivalent is the ActiveRecord finder methods. http://apidock.com/rails/ActiveRecord/Fixture/find

October 10, 2011 - (>= v3.1.0)
1 thank

Use Ruby instead!

E.g.

class TestClass < SomeSuperClass
  attr_accessor :sample_acc

  def initialize      
    @sample_acc = []
    super
  end
end

If nil is not a valid value for this accessor, then you can just define reader for it.

class TestClass
  attr_accessor :sample_acc

  def sample_acc
    @sample_acc ||= 98
  end
end
October 8, 2011
6 thanks

Undocumented :location option

You can use undocumented :location option to override where respond_to sends if resource is valid, e.g. to redirect to products index page instead of a specific product’s page, use:

respond_with(@product, :location => products_url)  
October 7, 2011
3 thanks

How to submit current url

For example to change some kind of param on select change…

<%= form_tag({}, {:method => :get}) do %>
  <%= select_tag :new_locale, options_for_select(I18n.available_locales, I18n.locale), :onchange => "this.form.submit();" %>
<% end %>
October 6, 2011
1 thank

Difference in the way returns are handled

Also, there is a difference in the way returns are handled from the Proc. A return from Proc.new returns from the enclosing method. Return in lambda-block acts like in regular method.

return example

def proc_return
  Proc.new { return "Proc.new"}.call
  return "proc_return method finished"
end

def lambda_return
  lambda { return "lambda" }.call
  return "lambda_return method finished"
end
puts proc_return
puts lambda_return
# => Proc.new
# => lambda_return method finished
October 4, 2011
1 thank

Unexpected rounding behavior

Both 2.5 and 1.5 are rounded to 2…

ree-1.8.7-2010.02 > sprintf("%.f", 0.5) 
=> "0" 
ree-1.8.7-2010.02 > sprintf("%.f", 1.5)
=> "2" 
ree-1.8.7-2010.02 > sprintf("%.f", 2.5)
=> "2" 
ree-1.8.7-2010.02 > sprintf("%.f", 3.5)
=> "4" 
ree-1.8.7-2010.02 > sprintf("%.f", 4.5)
=> "4" 

use round instead to get proper behavior

October 4, 2011
2 thanks

How to change format automatically depending on locale...

… without passing locale option.

In your application_helper.rb (or in other helper) place following code:

def number_to_currency(number, options = {})
  options[:locale] ||= I18n.locale
  super(number, options)
end

Then, in your locale files:

en-GB:
  number:
    currency:
      format:
        format: "%n %u"
        unit: "USD"

And that is it :)