Flowdock

Recent notes

RSS feed
September 30, 2009
2 thanks

See also: ActiveRecord::Base#increment

This is a class-level method. For the instance-level equivalent see: ActiveRecord::Base#increment

item = Item.find(1)
item.foo_count # => 0
Item.increment_counter(:foo_count, 1)
item.foo_count # => 0
item.reload
item.foo_count # => 1
item.increment(:foo_count)
item.foo_count # => 2
September 29, 2009
1 thank

Passing parameters to before_filter

I’ve found on the net 2 ways to pass parameters to before_filter:

method 1:

before_filter do |c|
c.class.module_eval do
private
def custom_filter
authorize(args)
end
end
end
before_filter :custom_filter

method 2:

before_filter do |c|
c.send(:authorize, args)
end
September 28, 2009
1 thank

Shortcut

According to http://henrik.nyh.se/2008/01/surround-helper-alternative-in-haml there is a short version for sprintf:

“(%s)” % “foo” is the same as sprintf(“(%s)”, “foo”)

Can someone who knows write more about this here? How do I work with multiple strings? Is this even possible? “(%s %t)” % “foo”, “bar” does not work.

September 24, 2009 - (>= v2.2.1)
0 thanks
September 24, 2009 - (>= v2.2.1)
0 thanks
September 24, 2009 - (>= v2.2.1)
0 thanks
September 24, 2009 - (>= v2.2.1)
0 thanks
September 24, 2009 - (>= v2.2.1)
0 thanks
September 24, 2009 - (>= v2.2.1)
0 thanks
September 24, 2009 - (>= v2.2.1)
0 thanks
September 24, 2009 - (>= v2.2.1)
0 thanks
September 24, 2009 - (>= v2.2.1)
0 thanks
September 24, 2009 - (>= v2.2.1)
0 thanks
September 24, 2009 - (>= v2.2.1)
2 thanks
September 24, 2009 - (>= v2.2.1)
0 thanks
September 24, 2009 - (>= v2.2.1)
0 thanks
September 18, 2009 - (>= v2.3.2)
0 thanks

Regenerate the JavaScript after each RJS call

RISCfuture - I had trouble using sortable_element_js in my rjs (javascript error when I used options), but had success with page.sortable(‘the_id’,{a_hash_of_my_options}) in my rjs

September 14, 2009
6 thanks

Pluralize Without Count

Helper method that returns the word without the count.

application_helper.rb

def pluralize_without_count(count, noun, text = nil)
  if count != 0
    count == 1 ? "#{noun}#{text}" : "#{noun.pluralize}#{text}"
  end
end

Example usage:

_form.html.erb

<%= pluralize_without_count(item.categories.count, 'Category', ':') %>
September 9, 2009
3 thanks

Will discard any order option

order_by(:created_at).find_each == FAIL!!!

class ActiveRecord::Base
  # normal find_each does not use given order but uses id asc
  def self.find_each_with_order(options={})
    raise "offset is not yet supported" if options[:offset]

    page = 1
    limit = options[:limit] || 1000

    loop do
      offset = (page-1) * limit
      batch = find(:all, options.merge(:limit=>limit, :offset=>offset))
      page += 1

      batch.each{|x| yield x }

      break if batch.size < limit
    end
  end
end
September 9, 2009
1 thank

extend adds class methods too

Because classes are objects. So for example:

module Ispeak
  def says
    "greetings aliens!"
  end
end

module Ieat
  def eats
    "spinach"
  end
end

module Inhabitant
  def says
    "I'm strong to the finish"
  end
end

class Human
  extend Ispeak # add class methods from Ispeak
  include Inhabitant # add instance methods from Inhabitant
end

Human.extend Ieat # add class methods from Ieat

puts Human.says # -> greetings aliens!
puts Human.eats # -> spinach

popeye = Human.new

puts popeye.says # -> I'm strong to the finish
September 9, 2009
2 thanks

Attachment's name

Files attached in a standard way are shown up as “noname”. You can specify any name by using the :filename key:

attachment :content_type => "application/pdf",
           :filename     => "Othersheet.pdf",
           :body         => File.read("example.pdf")
September 7, 2009
0 thanks

:popup gotcha in IE

If your popup title contains spaces or escaped HTML characters, Internet Explorer (at least 6/7) will not pop up a new window but open the link in the existing browser window.

September 6, 2009
0 thanks

Add last_week to core_extensions

If you want to implement last_week as posted by Mange, save it as:

lib/core_extensions.rb

class Date
  def last_week(day = :monday)
    days_into_week = { :monday => 0, :tuesday => 1, :wednesday => 2, :thursday => 3, :friday => 4, :saturday => 5, :sunday => 6}
    result = (self - 7).beginning_of_week + days_into_week[day]
    self.acts_like?(:time) ? result.change(:hour => 0) : result
  end
end

And add to:

config/environment.rb

require 'core_extensions'
September 1, 2009 - (>= v2.3.2)
1 thank

session expiration

If you need to set expiration period for sessions through all controllers in your application, simply add the following option to your config/intializers/session_store.rb file:

:expire_after => 60.minutes

If you need to set different expiration time in different controllers or actions, use the following code in action or some before_filter:

request.session_options = request.session_options.dup
request.session_options[:expire_after] = 5.minutes
request.session_options.freeze

Duplication of the hash is needed only because it is already frozen at that point, even though modification of at least :expire_after is possible and works flawlessly.

from - http://squarewheel.pl/posts/3

August 26, 2009
0 thanks

Passing an :object to the partial

For some reason the :object option is completely undocumented. Here’s an example usage.

# Renders the partial, making @new_person available through the local variable 'person'
render :partial => "person", :object => @new_person

(Credit goes to Catfish for the example, which I obtained from http://dev.rubyonrails.or/ticket/8518 )

August 26, 2009 - (v1.0.0 - v2.3.2)
2 thanks

sending an array of multiple options

To make sure that you’ll receive a array you should declare the name of the select with “[ ]” like that:

Example

<%= select_tag "users[]", options_for_select(@users.collect{|x| [x.name,x.id]}), {:multiple => :multiple, :size => 10} %>
August 24, 2009
1 thank

Getting (n..end)

It would seem like it would be possible to say, get everything from element i and to the end by saying

# WRONG!
a[i, -1] # "From 2 to the last element"

but since the second parameter does not say the ending index, but instead the length, this is not possible and you will get nil from the above code.

What you should do instead is using that the length can be specified longer then how long it is going to be:

b = [1, 2, 3]
# Return up to a million elements
# (not "return an array WITH 1 million elements")
b[2, 1_000_000] #=> [3]

# Size is guaranteed to never be shorter
# than our returned value should be
a[i, a.size]

It is a waste to do something like this:

a[i, a.size - i]
a[i..(a.size-i)]
August 21, 2009
1 thank

How not to find an element

assert_select ‘div’, :count => 0

August 21, 2009
2 thanks

Passing parameters to custom formbuilders

If you implement your own formbuilder, the options passed are available as @options inside your formbuilder. If you want those configuration options passed to all builders in the fields_for sections, use the following code in your form builder:

def fields_for_with_options(record_or_name_or_array, *args, &block) options = args.extract_options! fields_for_without_options(record_or_name_or_array, *(args << options.merge(@options)), &block) end alias_method_chain :fields_for, :options

Usage:

form_for @my_object, :builder => MyCustomFormbuilder, :some_setting => :cool