Equivalent scrapbook

…scrap on Model

complex scope example

class Document
  scope :with_latest_super_owner, lambda{ |o|
    raise "must be client or user instance" unless [User, Client].include?(o.class)
    joins(:document_versions, document_creator: :document_creator_ownerships).
    where(document_creator_ownerships: {owner_type: o.class.model_name, owner_id: o.id}).
    where(document_versions: {latest: true}).group('documents.id')
  }
end
# it can get kinda complex :)

filtering callbacks

a = DocumentName._save_callbacks.select{|cb| cb.kind.eql?(:after) }.collect(&:filter)

filtering callbacks that have conditon methods

a = DocumentName._save_callbacks.select{|cb| cb.kind.eql?(:after) and cb.options[:if].include? :my_super_evil_method_true?}.collect(&:filter)
a = DocumentName._save_callbacks.select{|cb| cb.kind.eql?(:after) and cb.options[:unless].include? :my_super_evil_method_true?}.collect(&:filter)

defining dynamic methods from array

  class Permission < ActiveRecord::Base
    DESIRED_PERMISSIONS=[:email, :user_interests, :user_checkins, :publish_stream]

    DESIRED_PERMISSIONS.each do |meth|
      define_method :"#{meth.to_s}?" do
        ! (  data[meth.to_s].blank? || data[meth.to_s] == 0 )
      end
    end
  end

order

rails 3

  Category.order("id DESC")

rails < 3

  Category.find(:all, :order => "id DESC")

how to prevent callbacks

preventing callbacks like after_create

Vote.skip_callback(:save, :after, :add_points_to_user)  #rails 3 
Vote.set_callback(:save, :after, :add_points_to_user)  #rails 3 

Foo.after_save.reject! {|callback| callback.method.to_s == 'some_method_name' }

http://stackoverflow.com/questions/1342761/how-to-skip-activerecord-callbacks
http://blog.viarails.net/2009/1/29/disabling-callbacks-in-an-activerecord-data-migration

to set them back (f.e. rspec after :each ) do

Vote.add_callback(:save, :after, :add_points_to_user)  #rails 3

be sure you using wright method ,create and save are 2 different things

how to monkeypatch

see this scrap

direct sql call

ActiveRecord::Base.connection.execute("decs relationships;")

class methods

    class << self
       my_class_method
    end

rise exeption if class wrong

      raise "Expecting auth handle of type #{expected_auth_handler_klass} but got #{auth_handler.class}" unless auth_handler.is_a?(expected_auth_handler_klass)

how to check if object or class responds to method or have column

At the class level you can do:

  Number.column_names.include? attr_name

If you have an instance, you can do:

 number.attributes.has_key? attr_name.

also you can do for method

 if self.respond_to? :safe_helper
   safe_helper
 end

rails 3 named_scope (scope)

polymorphic

    | Field                | Type         | Null | Key | Default | Extra          |
    +----------------------+--------------+------+-----+---------+----------------+
    | id                   | int(11)      | NO   | PRI | NULL    | auto_increment |
    | name                 | varchar(255) | YES  |     | NULL    |                |
    | created_at           | datetime     | YES  |     | NULL    |                |
    | notified_object_id   | int(11)      | YES  |     | NULL    |                |
    | notified_object_type | varchar(255) | YES  |     | NULL    |                |
    +----------------------+--------------+------+-----+---------+----------------+jj
  has_many :notifications, :class_name => "Notification::NewRecommendation", :foreign_key => :notified_object_id, :conditions => [ "notified_object_type = ?", self.to_s ]
  has_many :platform_identities, :class_name => "::PlatformIdentities::Base"
scope :visible, where("hidden != ?", true)
scope :published, lambda { where("published_at <= ?", Time.zone.now) }
scope :recent, visible.published.order("published_at desc")

with scope

examp1

def self.current_announcements(hide_time)
  with_scope :find => { :conditions => "starts_at <= now() AND ends_at >= now()" } do
                if hide_time.nil?
                  find(:all)
                else
                                      find(:all, :conditions => ["updated_at > ? OR starts_at > ?", hide_time, hide_time])
                end
    end
end

named scope (rc 108)

examp1

class Product < ActiveRecord::Base
    belongs_to :category
    named_scope :cheep, :conditions => {:price => 0..5 }
    named_scope :recent, lambda { {:conditions => ["released_at > ?", 2.weeks.ago]} }
  named_scope :recent, lambda { |*args| {:conditions => ["released_at > ?", (args.first || 2.weeks.ago)]} }  
    named_scope :visible, :include => :category, :conditions => { 'categories.hidden' => false }    #Najde tie ktore niesu v hidden kategoriach
end
  #pak mozem volat nieco ako 
    Product.vissible.count
    Product.cheep.all(:order => 'name')

examp2

  named_scope :on_date, Proc.new {|date|
    date = case date
    when :filter_7_days
      Date.today..(Date.today + 7.days)
    when :filter_30_days
      Date.today..(Date.today + 30.days)
    when :filter_3_months
      Date.today..(Date.today + 3.months)
    when :filter_half_year
      Date.today..(Date.today + 6.months)
    else
      date
    end
    {:conditions => {:on => date}}
  }