Flowdock

Recent notes

RSS feed
January 27, 2012
0 thanks

Example Usage

End of Day for Any Date

DateTime.new( 2011, 01, 01 )
# => Sat, 01 Jan 2011 00:00:00 +0000

DateTime.new( 2011, 01, 01 ).end_of_day
# => Sat, 01 Jan 2011 23:59:59 +0000

With Local Timezone

DateTime.civil_from_format( :local, 2011, 01, 01 ).end_of_day
# => Sat, 01 Jan 2011 23:59:59 -0700
January 20, 2012 - (>= v3.0.0)
0 thanks

Stubs Logger in rspec

Let we have a module like below:

module MyModule
  class << self
    def logger
      @logger ||= Logger.new(File.join(Rails.root, "log", "my_gem_#{Rails.env}.log"))
    end
  end
end

To use this logger just type:

MyModule.logger.info "This is a log line"

To stub in tests use (for rspec):

require 'active_support/log_subscriber/test_helper'

RSpec.configure do |config|
   config.include ActiveSupport::LogSubscriber::TestHelper

   config.before do
      MyModule.stub!(:logger).and_return(MockLogger.new)
   end
end

Usefull in testing when you don’t like to log anything.

January 20, 2012
1 thank

Example

Check if id column exists in users table

ActiveRecord::Base.connection.column_exists?(:users, :id)
January 19, 2012
1 thank

Pluralize with Text.

Example

1 person or 3 people

Use a View Helper

pluralize( 1, 'person' )
# => 1 person

pluralize( 2, 'person' )
# => 2 people

# In practice.
pluralize( Person.count, 'person' )

See

http://apidock.com/rails/ActionView/Helpers/TextHelper/pluralize

January 19, 2012 - (v3.0.0 - v3.1.0)
0 thanks

Options

I came across the following situation An article has a history of friendly url being that the foreign key that represents the value of the article’s id in the table is called Friend url_id then in that case:

Article.joins(“INNER JOIN friends ON articles.id = friends.url_id”).where(“friends.url like ? ”, url)

if the column url_id was renamed for artigo_id would be easier

Article.joins(:friend).where(“friends.url like ? ”, url)

January 16, 2012
0 thanks

form_for with :as routing

The following will not work if your post model is routed with the :as option:

form_for(@post)

Instead, use the helper with your custom name:

form_for(@post, :url => edit_renamedpost_path(@post))
January 16, 2012
1 thank

Model objects routed with :as

When providing a model object, url_for will not work if the model’s routes are named using the :as option. You can instead use the named helper methods (posts_path, post_path(:id), etc.).

January 11, 2012
0 thanks

Total Unique Elements: Set Union

For total unique elements, see set union: http://apidock.com/ruby/Array/|

January 10, 2012
0 thanks

with a params constant

If you want to have a params with the same value on all of the urls in this namespace, you can write this :

with a constant param :admin set to true

namespace :admin, :admin => true do
  resources :posts
end

all of the urls like /admin/post have a param :admin with the value true.

It works also with :

scope 'admin', :admin => true do
 ...
end

match 'administration', :admin => true => 'posts#index'

get 'administration', :admin => true

etc…

January 10, 2012
0 thanks

Set ids when using a collection of values (cont.)

Concerning greeneggs614’s post:

The following version would be a bit more intention revealing while providing the same output:

<% Car.each do |c| %>
  <%= check_box_tag "car_ids[]", c.id, :id => "car_ids_#{c.id}" %>
<% end %>
January 10, 2012
2 thanks

Will discard :select

Only does

SELECT model.id FROM models_table

regardless of select options

January 5, 2012 - (>= v3.0.9)
0 thanks

How to include a “Please select…” (default/prompt) in a grouped dropdown list.

The clue here is that you actually specify the prompt on the select element, and not in the option_groups_from_collection_for_select element.

<%= f.select :post_type_id,   option_groups_from_collection_for_select(@categories, :post_types, :name, :id, :name), :include_blank => "Please select..." %>

Hope this helps someone.

January 4, 2012
0 thanks

Total Unique Elements from Two Arrays

Simple but thought it was worth mentioning:

( [ 1, 2, 3 ] + [ 3, 4, 5 ] ).uniq    #=> [ 1, 2, 3, 4, 5 ]
January 4, 2012 - (v1_9_2_180)
0 thanks

Usage

I use this in views when I need to join a array of objects from a sql request here is a basic version of what I mean.

Code example

<%= @blogs.map{ |blog| blog.comment }.join(“ | ”) %>

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 30, 2011
0 thanks

See also: sample

sample randomly picks 1 or n elements from the array

December 29, 2011
0 thanks

Use kill 0 to find out if process is running

is_running.rb:

#!/usr/bin/env ruby

pid = ARGV[0].to_i

begin
  Process.kill(0, pid)
  puts "#{pid} is running"
rescue Errno::EPERM                     # changed uid
  puts "No permission to query #{pid}!";
rescue Errno::ESRCH
  puts "#{pid} is NOT running.";      # or zombied
rescue
  puts "Unable to determine status for #{pid} : #{$!}"
end

Thanks to http://stackoverflow.com/a/200568/51209

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 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).