code snippets 5#

init#

lazy instantiation#

Instead of lumping everything into initialize(), could use

def voice_mails
    @voice_mails || = []
    end

Works, except when nil or false are valid values for the attribute. In that case use the following more solid idiom

Class Employee...
    def assistant
        unless instance_variable_defined? :@assistant
            @assistant = Employee.find_by_boss_id(self.id)
            end
            @assistant
        end
    end
end

looks like OI (unassigned)

Eagerly initialised attribute#

Init an attribute at construction time

Class Employee
    def emails
        @email ||= []
    end
end

Nice to know coding things#

"main#home"     ~= {(controller: => "main", :action => "home)}   class:method
"main#home", :as => "homepage",specifies the named route "homepage_url"

> MainController.action(:home)

#

rails c --sandbox

More#

Caching#

Class TrackListen < ActiveRecord::Base
    acts_as_cached

in /app/controllers/homepage_controller.rb, change

class HomePageController.rb
def index
    @most_recent_listens = TrackListen.most_recent_listens
    render :text => ""
end

to

@most_recent_listens = TrackListen.cached(:most_recent_listens)

You pass the name of your custom_finder to cached method, which will resolve to call the method if the data is not to hand in cache.

class TrackListen < ActiveRecord::Base
    belongs_to :user

    def most_recent_listens
        TrackListen.find(:all, :order =>'created_at DESC', :limit=> 1000)
    end
end
class CreateTrackListens < ActiveRecord::Migration
    def self.up
        create_table :track_listens do |t|
            t.integer :user_id
            t.string :track_name
            t.timestamps
        end
    end
end

/app/models/user.rb

class User < ActiveRecord::Base
    has_many :track_listens
end

load_data.rb

User.destroy_all
TrackListen.destroy_all

1.upto(5) do |number|
    puts "Creating User ##{number}"
    u = User.create!(:name =>"Test User #{number}", :login =>"user_#{number}")
    total = 20000
    total.times do |i|
        puts "#{i} of #{total} TrackListens created" if (i % 4000 == 0)
        u.track_listens.create!(:track_name=>Track song #{rand(300)}")
    end
end

OMore code for later#

#!/usr/bin/env ruby

require 'pry'
require 'random_utils.rb'
a = SuccessChecker.new
binding.pry

over dir#

#!/usr/bin/env ruby
# iterate over all markdown files in current directory

Dir.glob('*.md').each do |some_file|
  puts "#{some_file}: #{File.read(some_file)}"
end