MySelf.to_s

Nearly everybody is convinced that every style but their own is ugly and unreadable. Leave out the “but their own” and they’re probably right…

MicroMachine

Minimal (32 LOC) Finite State Machine

class Event < ActiveRecord::Base
  def confirm!
    confirmation.trigger(:confirm)
  end

  def cancel!
    confirmation.trigger(:cancel)
  end

  def reset!
    confirmation.trigger(:reset)
  end

  def confirmation
    @confirmation ||= begin
      confirmation = MicroMachine.new(confirmation_state || "pending")
      confirmation.transitions_for[:confirm] = { "pending" => "confirmed" }
      confirmation.transitions_for[:cancel] = { "confirmed" => "cancelled" }
      confirmation.transitions_for[:reset] = { "confirmed" => "pending", "cancelled" => "pending" }
      confirmation.on(:any) { self.confirmation_state = confirmation.state }
      confirmation
    end
  end
end

App Settings using ActiveRecord

# app/models/settings.rb
class Settings < ActiveRecord::Base
  validates_presence_of :name, :value
  validates_uniqueness_of :name

  class << self
    def [](name)
      Settings.find_by_name(name).value rescue nil
    end

    def []=(name, value)
      setting = Settings.find_by_name(name) || Settings.new(:name => name)
      setting.value = value
      setting.save!
      value
    end
    
    def delete(name)
      Settings.delete_all(:name => name)
    end
  end

end

fix.to_s(base=10) → string

Returns a string containing the representation of fix radix base (between 2 and 36).

   12345.to_s       #=> "12345"
   12345.to_s(2)    #=> "11000000111001"
   12345.to_s(8)    #=> "30071"
   12345.to_s(10)   #=> "12345"
   12345.to_s(16)   #=> "3039"
   12345.to_s(36)   #=> "9ix"

Sequel: The Database Toolkit for Ruby

require 'rubygems'
require 'sequel'

DB = Sequel.sqlite # memory database

DB.create_table :items do
  primary_key :id
  String :name
  Float :price
end

items = DB[:items] # Create a dataset

# Populate the table
items.insert(:name => 'abc', :price => rand * 100)
items.insert(:name => 'def', :price => rand * 100)
items.insert(:name => 'ghi', :price => rand * 100)

# Print out the number of records
puts "Item count: #{items.count}"

# Print out the average price
puts "The average price is: #{items.avg(:price)}"

Connecting to a database

(Source: github.com)