Flowdock

Recent notes

RSS feed
October 16, 2013
0 thanks

Erb tags

The <% -%> is not being used since Rails 3.

The example above should be changed to:

<%= form_tag('/posts') do %>
  <div><%= submit_tag 'Save' %></div>
<% end %>
October 11, 2013 - (<= v3.2.13)
0 thanks

Bug - this is not working as documented

The stacking of several after_commit lines is not working. The last line overwrites the ones before.

Using an array for the :on options is also not working.

For details look here: http://github.com/rails/rails/issues/988#issuecomment-12653474

October 10, 2013
0 thanks

Classy guys...

:fav_bra_size - really?

October 2, 2013
0 thanks

You have explain well

You have explain well about fragment caching as I was in need of this information. http://autobodycarparts.com

October 2, 2013
0 thanks

Statistics

Thanks for the coding part it was really helpful for me, I would apply it on my project. http://www.koolchart.com

October 1, 2013
0 thanks

Update multiple attributes with raw sql

You can update multiple attributes with sql for each record being updated by using the following syntax:

example

Model.update_all("foo = 'bar', baz = 'bat'")
September 27, 2013
0 thanks

Using find_index to return first match. Profit!

This example shows how to use find_index to return a result as soon as the first occurrence of what you are looking for is found.

Code example

class Widget < Struct.new(:name, :profit); end

class WidgetManager
  def initialize(*widgets)
    @widgets = widgets
  end
  def is_any_widget_profitable?
    @widgets.find_index { |w| w.profit > 0 }  # <== usage!
  end
end

wm = WidgetManager.new(Widget.new('a', -100), Widget.new('b', 200), Widget.new('c', 300))
wm.is_any_widget_profitable?  # => 1
(wm.is_any_widget_profitable?) ? 'some profit' : 'all loss'  # => "some profit"

wm = WidgetManager.new(Widget.new('a', -100), Widget.new('b', -200), Widget.new('c', -300))
wm.is_any_widget_profitable?  # => nil
(wm.is_any_widget_profitable?) ? 'some profit' : 'all loss'  # => "all loss"
September 25, 2013
0 thanks

Anothery way

This Worked For Me

require File.expand_path('../app/models/extenstions/active_record_ext', File.dirname(__FILE__))

I did this in application.rb

September 24, 2013
0 thanks

Missing documentation for options hash

The deprecated function (http://apidock.com/rails/ActiveRecord/Serialization/to_json) has more useful documentation for the options hash.

September 13, 2013
0 thanks

Edge case

NilClass#try doesn’t check for methods on itself:

nil.blank?        #=> true
nil.try :blank?   #=> nil
September 11, 2013 - (v3.2.13)
0 thanks

touch in rails

touch is used to update the updated_at column you can create a model instance and update the updated_at value on it

Let say we have one user model

user = User.first

next you can write

user.touch

so it will run the query for you

UPDATE `users` SET `updated_at` = ‘current_date_time’ WHERE `users`.`id` = 1

Alternatively, to update some other column with the current date and time use:

model.touch(:column_name)

September 9, 2013
1 thank

Using reject to remove key/value pairs from a hash

Code example

# Remove empty strings
{ a: 'first', b: '', c: 'third' }.reject { |k,v| v.empty? } #=> {:a=>"first", :c=>"third"}

# Remove nil
{a: 'first', b: nil, c: 'third'}.reject { |k,v| v.nil? } # => {:a=>"first", :c=>"third"}

# Remove nil & empty strings
{a: '', b: nil, c: 'third'}.reject { |k,v| v.nil? || v.empty? } # => {:c=>"third"}
September 8, 2013
0 thanks

without a bang

We can use hash#slice if we want an Hash#extract (without bang) like behavior.

August 24, 2013
1 thank

expires_in option

@concept47 do you really need to check the fragment in the controller?

ActiveRecord will execute the query when its used

cars = Car.where(:colour => 'black') # No Query
cars.each {|c| puts c.name } # Fires "select * from cars where ..."

“Lazy Loading” - http://m.onkey.org/active-record-query-interface

August 20, 2013
1 thank

everything is ok

Olefine, I’m not sure here is a good place for such questions (better use stackoverflow for example), but answer for your question is that Rails provide slice (and many other methods) not only for Hash class but for HashWithIndifferentAccess too such as for any other superclass of Hash, so they use

hash = self.class.new

for a reason. {} is a literal only for Hash.

August 17, 2013
0 thanks

for finding content

it will use all the field related to particular table so you can find data by any table field like Table name => ABC(:id, :name, :address) if you want to find data related to id or name or address than only write

ABC.find_by_id(1)

ABC.find_by_name(“abc”)

ABC.find_by_address(“abc”)

find_by_field_name will find only first data match with it

if u want to find all data than enter

ABC.find_all_by_id(1)

ABC.find_all_by_name(“abc”)

ABC.find_all_by_name(“abc”)

August 15, 2013 - (v3.2.1 - v3.2.13)
0 thanks

expires_in option

You can actually pass in an expires_in option that sets how long Rails should show the fragment before deleting it so as an example …

<% cache('homepage_sidebar', :expires_in => 10.minutes) do %>
  <div>
    ...
  </div>
<% end %>

This only used to work with memcached but it now works with other types of Rails stores, MemoryStore, FileStore (had to use a plugin to get this behavior before) etc etc

So in your controller. You’d just do …

@posts = Posts.all if fragment_exists?('homepage_sidebar') 

to avoid performing a pointless SQL query.

August 12, 2013
0 thanks

unuseful code

Why it use?

hash = self.class.new

Instead it, we may use

hash = {}
August 7, 2013
0 thanks

Not Supported on Memcached.

Just an FYI, this is not supported on Memcached, so I would avoid it if you’re using FileStore and are planning on moving over to Memcached eventually.

July 25, 2013
0 thanks
July 23, 2013
0 thanks

Use strings as parameters, not booleans

I just stumbled across this somewhere in our codebase. The first example is faulty, the second one is correct.

= f.check_box :public, {}, true, false
# <input id="event_public" name="event[public]" type="checkbox" value="true" />

and:

= f.check_box :public, {}, "true", "false"
# <input name="event[public]" type="hidden" value="false" />
# <input id="event_public" name="event[public]" type="checkbox" value="true" />
July 18, 2013 - (v3.2.1 - v3.2.13)
0 thanks

Nested i18n attributes

If you want to use nested attributes in a i18n file (like person :has_many => :addresses), write:

en:
  activerecord:
    attributes:
      person:
        name:
      "person/addresses":
        street: "Street name"
      "person/phones":
        area: "Area code"
        number: Number
July 16, 2013 - (>= v3.2.1)
0 thanks

Difference between fullpath

From what I’ve seen, it looks like the difference between this and #fullpath is that this method doesn’t include parameters that weren’t in the original url (i.e. parameters that were sent via POST instead of GET).

July 16, 2013
0 thanks

isolate_namespace description with example

Normally when you create controllers, helpers and models inside an engine, they are treated as if they were created inside the application itself. This means that all helpers and named routes from the application will be available to your engine’s controllers as well.

However, sometimes you want to isolate your engine from the application, especially if your engine has its own router. To do that, you simply need to call isolate_namespace. This method requires you to pass a module where all your controllers, helpers and models should be nested to:

module MyEngine
 class Engine < Rails::Engine
   isolate_namespace MyEngine
 end

end

With such an engine, everything that is inside the MyEngine module will be isolated from the application.

Detail reference: http://edgeapi.rubyonrails.org/classes/Rails/Engine.html

July 12, 2013 - (1.1.4 - 1.3.1)
1 thank

correct, but ..

stub_chain provides a very good replacement of long lines of nested stubs, but never forget it violates Law of Demeter; i.e. it indicates an increase of coupling in your classes and this is a bad thing because it means your objects now are making more unnecessary calls to other objects. for example:

def initialize(some_obj)
  @obj = some_obj
end

def foo
  @obj.x  # GOOD coupling - according to LoD you are allowed to call a method on your object
end

def bar
  @obj.x.y   # BAD coupling - can not call a method on a returned value of another method call even if the initial call is legal
end

How is this related to TDD and stubs?

  • method foo test will have only one stub for a double of some_obj type

  • method bar will have 2 stubs: the first is going to swallow the other one to produce the result (and then can be shortened using this stub_chain technique)

Always remember: if your tests are using stub_chains –> your code is smelly and possibly tightly coupled.

July 12, 2013 - (v3.0.0 - v3.2.13)
0 thanks

Accept header ignored

Rails ignores the accept header when it contains “,/” or “/,” and returns HTML (or JS if it’s a xhr request).

This is by design to always return HTML when being accessed from a browser.

This doesn’t follow the mime type negotiation specification but it was the only way to circumvent old browsers with bugged accept header. They had he accept header with the first mime type as image/png or text/xml.

July 11, 2013
0 thanks

Using fields_for with collection (no association)

accepts_nested_attributes_for has some detractors: http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models

But fields_for is defined both on FormBuilder and FormHelper and is still useful even when accepts_nested_attributes_for is not being used. Consider a “to do list” application where we wish to edit and update a list of tasks (Task model). I like to use a TaskCollectionController to manage the actions on the collection, it feels more RESTful than overloading a TaskController:

class TaskCollectionController < ApplicationController
# task_collection_edit GET /task_collection/edit 
  def edit
    @tasks = Task.all
  end

# task_collection_update PUT /task_collection/update
  def update
    # it would be better to use a TaskCollection form object here
    # to make this controller skinny,
    # for the sake of brevity I skipped the form object
    params[:tasks].values.each do |attrs|
      if attrs[:_destroy] == '1'
        Task.find(attrs[:id]).destroy
      elsif attrs[:id].blank?
        Task.create(attrs.slice!(:id,:_destroy))
      else
        Task.find(attrs[:id]).update_attributes(attrs.slice!(:id,:_destroy))
      end
    end
    redirect_to task_collection_edit_path
  end
end

In the edit view, I use fields_for to index added tasks, and it also will insert the id as a hidden field for existing tasks:

%h1 Edit Task Collection
= form_tag task_collection_update_path, :method => :put do
  %table#tasks
    %tr
      %th Name
      %th Priority
    - @tasks.each do |task|
      = fields_for 'tasks[]', task, :hidden_field_id => true do |task_form|
        = render :partial => 'task_form', :locals => {:task_form => task_form}

  = button_tag 'Save'

= button_tag "Add task", :type => :button, :id => :add_task

%script{:type => 'html/template', :id => 'task_form_template'}
  = fields_for 'tasks[]', Task.new, :index => 'NEW_RECORD', :hidden_field_id => true do |task_form| render(:partial => 'task_form', :locals => {:task_form => task_form}); end

:javascript
  $(function(){
    task_form = function(){ return $('#task_form_template').text().replace(/NEW_RECORD/g, new Date().getTime())}
    var add_task = function(){ $('#tasks').append(task_form()) }
    $('#add_task').on('click', add_task)
  })

:hidden_field_id => true triggers the insertion of the id field, and a placeholder index “NEW_RECORD” is replaced by javascript when a task is added, as others have described here. When there’s no association, the index key is :index, vs. :child_index in the case of an association.

Here’s the partial used in the edit view:

%tr
  %td= task_form.text_field :name
  %td= task_form.select :priority, [1,2,3,4,5]
  %td= remove_item(task_form)

The remove_item helper triggers the deletion of persisted tasks:

module TaskCollectionHelper
  def remove_item(form_builder)
    if form_builder.object.new_record?
      # If the task is a new record, remove the div from the dom
      link_to_function( 'Remove', "$(this).closest('tr').remove()")
    else
      # However if it's a "real" record it has to be deleted from the database,
      # hide the form and mark for destruction
      form_builder.hidden_field(:_destroy) +
      link_to_function( 'Remove', "$(this).closest('tr').hide(); $(this).siblings().attr('value',1)")
    end
  end
end
June 26, 2013 - (v3.0.0 - v3.2.13)
0 thanks

IS NOT NULL or !=

where.not()

# SELECT `users`.* FROM `users` WHERE (`users`.`id` != 1) AND (`users`.`name` IS NOT NULL)
 User.where.not(id: 1).where.not(name: nil)