Flowdock

Notes posted to Ruby on Rails

RSS feed
December 31, 2011 - (v3.1.0)
0 thanks

Recommendations

I would just use the path_to_image. I find that this is what works best. As it says above it can create problems.

Here is my code

Code example

def background_path(background)
  if background
    path_to_image background.file_name.normal
  else
    path_to_image "background_preview.jpg"
  end
end

def flavor_path(flavor)
  if flavor
    path_to_image flavor.file_name.normal
  else
    path_to_image("flavor_preview.jpg")
  end
end

basic but gets the job done and it does not have problem with my pre built paths which are called image_path

December 17, 2011
1 thank

example

[‘one’,‘two’,‘three’].to_sentence # => “one, two, and three”

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 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
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)
1 thank

Rails

For Rails 3.1 check see:

http_basic_authenticate_with :name => "username", :password => "pass" 
November 12, 2011 - (v2.0.0 - 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
2 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.5 - 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
0 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
5 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
0 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 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 :)

October 3, 2011
0 thanks

@Mange

If you’re actually looking to cut down on code why not use .map instead of the longer .collect?

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

Using a block with image_tag

HTML5 officially supports block-level elements in the anchor tag and Rails 3 allows you to pass a block to image_tag:

<%= image_tag(some_path) do %>

<%= content_tag(:p, "Your link text here")

<% end %>

September 30, 2011 - (v3.0.0 - v3.1.0)
0 thanks

Without module

If you want to have only the path prefix without namespacing your controller, pass :module => false.

Normal:

namespace :account do
  resources :transactions, :only => [:index]
end

account_transactions GET /account/transactions(.:format)
{:controller=>"account/transactions", :action=>"index"}

With :module => false:

namespace :account, :module => false do
  resources :transactions, :only => [:index]
end

account_transactions GET /account/transactions(.:format)
{:controller=>"transactions", :action=>"index"}