Flowdock

Recent notes

RSS feed
January 27, 2010
1 thank

File name without the extension

To get the file name without the extension you can use File.extname in combination with File.basename

File.basename("test.rb", File.extname("test.rb"))             #=> "test"
File.basename("a/b/d/test.rb", File.extname("a/b/d/test.rb")) #=> "test"
File.basename("test", File.extname("test"))                   #=> "test"
File.basename(".profile", File.extname(".profile"))           #=> ".profile"
January 27, 2010
3 thanks
January 27, 2010
1 thank

Alternative hostname generation method

Instead of using a random number to generate the hostname for the single asset, I prefer using source.hash.modulo, so that a given file is always served from the same host. This makes the content more cacheable by browsers and proxies.

ActionController::Base.asset_host = Proc.new { |source|
  "http://assets#{ source.hash.modulo(9) }.example.com"
}

I didn’t benchmark how long it takes, but String#hash should be reasonably fast.

January 26, 2010 - (>= v2.3.2)
1 thank

is now a subclass of Hash that preserves order (or _is_ a Hash if running Ruby 1.9 or greater)

You might not realize it preserves order because it delegates inspect to its super-class, Hash, which doesn’t preserve order. But you will see that order is preserved if you iterate or use the keys or values methods:

>> names = ['Amy Irving', 'Jane Doe', 'John Doe', 'John Updike', 'Susan Anthony']
>> ordered = names.group_by { |name| name.split.first }
=> #<OrderedHash {"John"=>["John Doe", "John Updike"], "Amy"=>["Amy Irving"], "Susan"=>["Susan Anthony"], "Jane"=>["Jane Doe"]}>

>> ordered.keys
=> ["Amy", "Jane", "John", "Susan"]

>> ordered.each { |first, full| puts first; full.each { |name| puts "  "+name } }
Amy
  Amy Irving
Jane
  Jane Doe
John
  John Doe
  John Updike
Susan
  Susan Anthony
January 26, 2010 - (>= v2.3.2)
2 thanks

returns an ActiveSupport::OrderedHash

Returns an ActiveSupport::OrderedHash, which is a subclass of Hash that preserves order. If you’re running Ruby 1.9, it is simply an alias for Hash. Surprisingly, you might not realize that OrderedHash is preserving order since it delegates its inspect method to Hash. More at ActiveSupport::OrderedHash.

January 25, 2010
2 thanks

custom uniq method

Build hash from elements of your Array using attribute as key and the element as value and return values of Hash:

Hash[*ary.map {|obj| [obj.name, obj]}.flatten].values
January 22, 2010
1 thank

Interesting usage for polymorphic asset model :)

…to automatically define default scopes of inherited classes.

 class Asset < ActiveRecord::Base

  belongs_to :resource, :polymorphic => true
  before_save :set_asset_type

  def set_asset_type
   self.asset_type = self.class.name
  end

  def self.inherited(subclass)
    super
    subclass.send(:default_scope, :conditions => "asset_type='#{subclass.name}'")
  end
end
January 21, 2010
3 thanks

W3CDTF Format

Here is the formatted string for the W3CDTF datetime format (http://www.w3.org/TR/NOTE-datetime). It has a semicolon in the timezone part, therefore you cannot use ‘%z’:

Time::DATE_FORMATS[:w3cdtf] = lambda { |time| time.strftime("%Y-%m-%dT%H:%M:%S#{time.formatted_offset}") }
January 20, 2010
4 thanks

Using html text instead of default response

If you have a string containing html and want to assert_select against it, as the doc states you have to pass in an element (HTML::Node) as the first argument. You can do something like this:

doc = HTML::Document.new('<p><span>example</span></p>')
assert_select doc.root, 'span'
January 20, 2010
2 thanks

Escape brackets in selector

If you need to escape brackets in a selector, this is the way to do it:

assert_select "input[type=hidden][name='user[role_ids][]']"
January 20, 2010
3 thanks
January 19, 2010
2 thanks

Argument Accepted

Accepts a single argument record_separator which is the character or string to chomp.

Why isn’t this shown in the method def at the top?

January 19, 2010
2 thanks

Argument Accepted

Accepts a single argument sep_string

January 18, 2010
1 thank

Undeprecated version

The undeprecated version of this function is here: ActionView::Helpers::PrototypeHelper#link_to_remote

January 16, 2010 - (>= v2.2.1)
8 thanks

Pretty way to test for current environment

You can check your current Rails environment using nice methods such as:

Rails.env.development?
Rails.env.test?
Rails.env.production?
Rails.env.your_custom_environment?
January 15, 2010
3 thanks

Use this in controllers

Sometimes you’re gonna need this in controllers. Just put this in the controller:

include ActionView::Helpers::NumberHelper
January 14, 2010
0 thanks

:find takes more keys than written

The documentation says that the :find keywords “may include the :conditions, :joins, :include, :offset, :limit, and :readonly options”. Note that this does not mean that only those options are supported. :sort also works like it should, for example.

January 14, 2010
1 thank

Will this method get rid of existing data?

Will this method get rid of existing data?

January 11, 2010 - (>= v2.2.1)
2 thanks

Default fallback

You can specifly :default option which is useful when the translation is not found. For example:

t(:this_translation_doesnt_exist, :default => 'Ooops!')
# => Ooops!

Or even any number of “fallbacks” - the first not nil is returned:

t(:missing, :default => [:missing_too, :existing, 'Sad panda'])
# => :existing translation

Good introduction to Rails I18n is http://guides.rubyonrails.org/i18n.html

January 11, 2010
2 thanks
January 11, 2010
0 thanks

Includes all ancestors

May be helpful to know that this returns true if B is any ancestor of A, not just a direct one. As an example:

class Foo; end
class Bar < Foo; end
class Baz < Bar; end

Foo >= Bar #=> true
Foo >= Baz #=> true
January 11, 2010
0 thanks

Includes all ancestors

May be helpful to know that this returns true if B is any ancestor of A, not just a direct one. As an example:

class Foo; end
class Bar < Foo; end
class Baz < Bar; end

Foo > Bar #=> true
Foo > Baz #=> true
January 11, 2010
0 thanks

Includes descendants

May be helpful to know that this returns true if A is any descendant of B, not just a direct one. As an example:

class Foo; end
class Bar < Foo; end
class Baz < Bar; end

Bar <= Foo #=> true
Baz <= Foo #=> true
January 11, 2010
0 thanks

Includes descendants

May be helpful to know that this returns true if A is any descendant of B, not just a direct one. As an example:

class Foo; end
class Bar < Foo; end
class Baz < Bar; end

Bar < Foo #=> true
Baz < Foo #=> true

If you want direct descendance try Class#superclass:

Bar.superclass == Foo #=> true
Baz.superclass == Foo #=> false
January 8, 2010
1 thank

Status Codes

Full detail: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

  • 100 - Continue

  • 101 - Switching Protocols

  • 200 - OK

  • 201 - Created

  • 202 - Accepted

  • 203 - Non-Authoritative Information

  • 204 - No Content

  • 205 - Reset Content

  • 206 - Partial Content

  • 300 - Multiple Choices

  • 301 - Moved Permanently

  • 302 - Found

  • 303 - See Other

  • 304 - Not Modified

  • 305 - Use Proxy

  • 306 - No Longer Used

  • 307 - Temporary Redirect

  • 400 - Bad Request

  • 401 - Not Authorised

  • 402 - Payment Required

  • 403 - Forbidden

  • 404 - Not Found

  • 405 - Method Not Allowed

  • 406 - Not Acceptable

  • 407 - Proxy Authentication Required

  • 408 - Request Timeout

  • 409 - Conflict

  • 410 - Gone

  • 411 - Length Required

  • 412 - Precondition Failed

  • 413 - Request Entity Too Large

  • 414 - Request URI Too Long

  • 415 - Unsupported Media Type

  • 416 - Requested Range Not Satisfiable

  • 417 - Expectation Failed

  • 500 - Internal Server Error

  • 501 - Not Implemented

  • 502 - Bad Gateway

  • 503 - Service Unavailable

  • 504 - Gateway Timeout

  • 505 - HTTP Version Not Supported

January 6, 2010
6 thanks

Doesn't return nil if the object you try from isn't nil.

Note that this doesn’t prevent a NoMethodError if you attempt to call a method that doesn’t exist on a valid object.

a = Article.new

a.try(:author) #=> #<Author ...>

nil.try(:doesnt_exist) #=> nil

a.try(:doesnt_exist) #=> NoMethodError: undefined method `doesnt_exist' for #<Article:0x106c7d5d8>

This is on Ruby 1.8.7 patchlevel 174

January 6, 2010
1 thank

Alternative:

without using at

[:a, :b, :c].try(:[], 1)
December 31, 2009
2 thanks

Replacing with "\" and match — a simple solution

A somewhat different approach to the same problem:

v.gsub(/(?=\W)/, '\\') #=> Foo\ Bar\!

But from what you are trying to achieve I suspect you might be interested in Regexp.escape method :)

December 28, 2009
4 thanks

Attribute names are Strings, not Symbols

Another possible gotcha – the returned hash keys are of type String, not Symbol:

user.attributes["login"] # => "joe"
user.attributes[:login] # => nil