Recent notes

RSS feed
July 13, 2015
0 thanks

Correction to previous comment

You’ve misread the documentation, @sandyjoins. If you pass two arguments, the second one is a length argument, not an upper bound.

“Hello there”.byteslice(6, 1) == “t”

July 13, 2015 - (v1_9_3_392)
0 thanks

Important note!

Special cases:

Code example

Test”.byteslice(1, 3) => “est” #both limits inclusive

Test”.byteslice(0, 3) => “Tes” #upper limit exclusive

Test”.byteslice(0..3) => “Test” # Both limits inclusive

July 6, 2015
0 thanks

For supported arguments, see see match

As of July, 2015, the v4.2.1 doc says “see match[rdoc-ref:Base#match]” without a URL. I think you want this one: http://apidock.com/rails/ActionDispatch/Routing/Mapper/Base/match

July 2, 2015
0 thanks

Usage with enum

With enum fields you must use integer values:


Model.update_all(type: Model.types[specific_type])
July 1, 2015
0 thanks

Space before the opening [

In this example

Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]

The array is a parameter, so a space is required before the opening [, which is equivalent to write like this

Post.find_by_sql(["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date])
June 19, 2015
1 thank

Use :where or any defined scope before :find_or_create_by

You can chain find_or_create_by with :where, or any custom scope.


User.where(girls: true).find_or_create_by(first_name: ‘Scarlett’)

scope :celebrities, -> { where(celebrity: true) }

User.celebrities.create_with(last_name: ‘Johansson’).find_or_create_by(first_name: ‘Scarlett’)

June 9, 2015 - (v1.0.0 - v4.2.1)
0 thanks

Not a one-to-one-relationship

It’s incorrect to state that belongs_to “Specifies a one-to-one association with another class”.

If the inverse association is has_one then the model specifying belongs_to is the LHS of a zero/one-to-one relationship.

If the inverse association is has_many then the model specifying belongs_to is the LHS of a zero/many-to-one relationship.

Unless you know what the inverse association is, all you can assume is that instances of a class specifying a belongs_to association can be related to at most a single instance of the other class.

June 3, 2015 - (v4.0.2 - v4.2.1)
0 thanks

render with variables

perient view

Code example

<%= render 'time_select', locals: { select_name: 'from_tiem'}%>

render view

Code example

<%= locals[:select_name] %>


Code example

<%= local_assigns[:select_name] %> 
May 23, 2015 - (v1_9_3_392)
0 thanks


Reading source one can find detailed patterns: github.com/ruby/ruby/blob/ruby_1_9_3/lib/uri/common.rb

May 22, 2015 - (>= v1_8_6_287)
0 thanks

Not exactly like map {}.flatten

To also give dimension, is about 4.5 times faster then map {}.flatten.

May 18, 2015
0 thanks

Are those supported versions correct?

It seems like this method was supported in versions prior to 4.0.2.

UPDATE never mind, wish I could delete this comment..

May 12, 2015
0 thanks

RE: Convert an Array of Arrays to a Hash using inject

Another way to convert an array of arrays to a hash using inject:

array = [['A', 'a'], ['B', 'b'], ['C', 'c']]

hash = array.inject({}) do |memo, values|
  memo.merge!(values.first => values.last)

# => {'A' => 'a', 'B' => 'b', 'C' => 'c'}
May 8, 2015 - (>= v4.0.2)
0 thanks

This doesn't write files

This doesn’t write files, at least not anymore. Since at least rails 4 `Rack::Cache` isn’t included by default. In any case this method only ever set headers on the response.

May 1, 2015
2 thanks

Very bad documentation

This is terrible documentation. It makes it very hard to understand what the arguments mean.

The signature is

alias_method(p1, p2)

So what do p1 and p2 mean? The description doesn’t refer to them at all, but to new_name and old_name. How are we supposed to know which is which?

And then it gets even worse in the code sample:

alias_method :orig_exit, :exit

From the naming it sounds like the first argument is the original method name.

Documentation is supposed to resolve this kind of confusion, not create it.

April 29, 2015
0 thanks

Prevent new line character.

To prevent the “\n” character added at the end of each file pass in the “row_sep: nil” option:

[ "some", "array" ].to_csv                 # => "some, array\n"  

[ "some", "array" ].to_csv( row_sep: nil ) # => "some, array"
April 23, 2015
0 thanks

add index directly

You can add an index now directly on the foreign_key :

t.references(:user, index: true)
April 21, 2015
0 thanks

RSS feeds in Rails

Fetching RSS feeds in the request/response cycle inside a Rails application is probably not the very best approach, as it will make your application as slow as the server serving RSS feeds. Another option is to do it asynchronously using a worker or a queue, but this can also become quite complex and hard to maintain over time.

Another solution is to use an API like superfeedr.com and its Rails Engine (http://blog.superfeedr.com/consuming-rss-feeds-rails/). All the polling and parsing is done on Superfeedr’s side and your application is notified in realtime as soon as the resources are updated using a webhook pattern.

April 14, 2015
0 thanks


It still exists but you give it a block instead of creating a method:


def before_create
  self.login = self.first_name


before_create :set_login

def set_login
  self.login = self.first_name
April 8, 2015 - (v3.1.0 - v4.1.8)
1 thank

What object_name.method values will result in checked chekboxes.

*It’s intended that method returns an integer and if that integer is above zero, then the checkbox is checked.* - more exactly, that’s how it’s determined whether value will be checked or not:

(`@checked_value` is checked_value, `value` is what object_name.method returns)

def checked?(value)
  case value
  when TrueClass, FalseClass 
    value == !!@checked_value
  when NilClass
  when String
    value == @checked_value
    if value.respond_to?(:include?)
      value.to_i == @checked_value.to_i
April 2, 2015
0 thanks


“Acceptable exception types maye be given as optional arguments. If the last argument is a String, it will be used as the error message.”


“Acceptable exception types may be given as optional arguments. If the last argument is a String, it will be used as the error message.”

April 1, 2015 - (>= v4.1.8)
0 thanks

Parent associations are kept

Maybe this information will save you some time: parent associations (i.e. associations with foreign id in current record) are copied. Don’t assume you’ll get a safely editable object.

March 30, 2015
0 thanks

Passing a block does not behave as expected

When the condition is true, the block is not rendered:

<%= link_to_if true, users_path, {}, {} do %>
  <i class='fa fa-star'></i>
<% end %>


<a href="/users">/users</a>

But if the condition is false, the block will render:

<%= link_to_if false, users_path, {}, {} do %>
  <i class='fa fa-star'></i>
<% end %>


<i class='fa fa-star'></i>
March 30, 2015
0 thanks

If condition is false, options hash is ignored

Here, the class will be ignored:

<%= link_to_if false, 'Home', root_path, class: 'link' %> 
#=> Home
March 26, 2015
0 thanks

Save yourself a little typing

We often have a form with a select box that selects a model association. So for example to select a colour, when there is an associated Colour model, a select box will typically select :colour_id.

In this case, ActionView automatically humanizes :colour_id to produce “Colour” as the label text.

March 19, 2015
0 thanks

enumerator and number of lines to read


  .map do |line|
    # ... stuff ... 
March 19, 2015
0 thanks

Wrong number of arguments (2 for 1)

If you get this error, wrap brackets with parentheses: Post.find_by_sql([“some query”])

March 19, 2015 - (v4.0.2)
0 thanks

number_field tag does not accept the same options as text_field_tag

number_field_tag does not accept the size or maxlength options; the max option for number_field_tag is used to control the size of the field. According to W3 http://www.w3.org/TR/html-markup/input.number.html , placeholder should be accepted, but I don’t find that this works in the way it works for text_field_tag.

March 18, 2015
0 thanks

Transactions and Stale ORM Data

Consider the following:

foo = Foo.new
bar = Bar.new

ActiveRecord::Base.transaction do
  foo.save! # succeeds
  bar.save! # failure, validation problem

foo.persisted? # true (!)

foo was not permanently stored in the database, but it was transiently saved, and this is reflected in the ActiveRecord model still in memory. But if you try

foo.reload # raises ActiveRecord::RecordNotFound

Don’t let stale data confuse you after using transactions!

Edited to add: This particular example does not succeed in reproducing the issue I encountered, which involved a slightly more complicated set of nested transactions. I haven’t managed to produce a simple test case where stale data remains in the model, but I have definitely experienced it in my app.