A cheat sheet!
http://blog.nanorails.com/pages/rails-1-1-cheat-sheet
String:
quote = 'quotes are pretty basic but need to be lowercase'
Symbols:
:hamster
:cow
:guineapig
Constants:
EmpireStateBuilding = "350 5th Avenue, NYC, NY"
Methods:
front_door.open
front_door.open.close
front_door.is_open?
front_door.paint( 3, :red )
front_door.paint( 3, :red ).dry( 30 ).close()
Class Methods:
Door::new( :oak )
Global Variables:
$x, $1, $chunky and $CHunKY_bACOn are examples.
Instance Variables:
@x, @y
Class variables:
@@x, @@y
Blocks:
2.times { print "Yes, I've used chunky bacon in my examples, but never again!" }
Ranges:
(1..3) is a range, representing the numbers 1 through 3.
('a'..'z') is a range, representing a lowercase alphabet.
(0...5) represents the numbers 0 through 4.
Arrays:
[1, 2, 3] is an array of numbers.
['coat', 'mittens', 'snowboard'] is an array of strings.
Hashes:
{
'name' => 'Peter',
'profession' => 'lion tamer',
'great love' => 'flannel'
}
Emptyness:
plastic_cup = nil
plastic_cup = false
IF and UNLESS:
if plastic_cup
print "Plastic cup is on the up 'n' up!"
end
unless plastic_cup
print "Plastic cup is on the down low."
end
<%= link_to 'host', item.from if item.from != "" -%>
print "Yeah, plastic cup is up again!" if plastic_cup
print "Hardly. It's down." unless plastic_cup
print "We're using plastic 'cause we don't have glass." if plastic_cup unless glass_cup
**WHEY**
leading zeroes:
"%05d" % 200
gives "00200"
assigning dependent on...
at_hotel = true
email = if at_hotel
"why@hotelambrose.com"
else
"why@drnhowardcham.com"
end
--- looping through an array with a counter
<% @items.each_with_index do |item, index| %>
<%= index+1 %>.
<%= item.name %>
<% end %>
--- ANY ? ---
@sections.any? { |section| section.is_a?(String) }
--- IS AN ARRAY ? ---
@sections.is_a?(Array)
--- forms ---
<%= f.hidden_field :has_manufacture, :value => "No" %>
--- count() ----
nav_items = navItems.size
nav_items = navItems.length
--- if / else --
if x == y
beeroclock = 'now'
elsif
beeroclock = 'later'
else
beeroclock = 'over'
end
--- logging ---
logger.warn "Failed login for '#{params[:email]}' from #{request.remote_ip} at #{Time.now.utc}"
---- sorting and eaching ----
<% @posts = Post.find(:all, :order => 'created_at DESC') %>
<% @posts.each do |post| %>
something
<% end %>
---- more find examples ----
@items = @user.items.find(:all, :order => 'id DESC').paginate(:per_page => 100, :page => params[:page])
---- STRING MANIPULATION ----
truncate(neighbourhood.description, :length => 260)
pluralize(post.responses.size,'response')
----
to_formatted_s
to_param
to_query
to_sentence
to_xml
http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Array/Conversions.html#M000274
--- SCRIPT ---
script/server - start server
script/console - run console with all models...
script/server -p 3001 -d - run server on port 3001 and detatch the console
- ( use ps aux & kill to stop it )
script/server -p 3001 -e production - run server in production & on port 3001
--- DEBUGGING ---
In A View
<%= debug @object %>
<%= debug 'string' %>
<%= 'string'.inspect %>
In A Controller
logger.debug "The object is #{@object}"
RAILS_DEFAULT_LOGGER.debug @object
---- RAKE ----
rake -T ( is the shit )
install, unpack and build gems in a rails project:
rake gems:install
rake gems:unpack
rake gems:build
rake routes -- gets you all the routs in your project
point to -> production
rake db:migrate RAILS_ENV=production
clear ruby on rails cache
rake tmp:cache:clear
generate:
script/generate migration MyNewMigration
script/generate controller static
---- Mongrel ----
STOP MONGREL --daemon
http://www.cyberciti.biz/faq/kill-process-in-linux-or-terminate-a-process-in-unix-or-linux-systems/
-- kill deamon --
ps aux (to get the id)
kill id
-- SNIPS --
<%= link_to "#{image_tag("go_back.png")}Go Back", user_path(@user) %>
FINDERS ----------------------------
oldEntries = Posts.find( :all, :conditions => ['visible = ? and created_at <= ?', 'yes', (Time.now - daysToKeep.days)])
SCOPES -----------------------------
Inside the model:
default_scope :order => 'name ASC'
Entry.named_scope :lastweek, :conditions => ["created_at > ?", 7.day.ago]
Entry.named_scope :isvisible, :conditions => {:visible => 'yes'}
-- lambda makes sure the current date is uses and not a cached? one
Entry.named_scope :lastweek, lambda {
{:conditions => ["created_at > ?", 7.day.ago]}
}
-- Entries with AND ( headline AND blurb need to be 'bmx' )
Entry.scope_procedure :awesome, lambda { headline_like("bmx").blurb_like("bmx") }
-- Entries with OR ( headline OR blurb need to be 'bmx' )
Entry.scope_procedure :awesome, lambda { headline_like_or_blurb_like("bmx") }
Entry.named_scope :with_recent_orders, :conditions => ["comments.created_at >= ?", 1.week.ago]
RENDER --------------------------
render :partial => "person", :locals => { :name => "david" }
render :partial => "person", :object => @new_person
render :partial => "person", :collection => @winners
render :partial => "admin_person", :collection => @winners, :as => :person
render :partial => "person", :collection => @winners, :spacer_template => "person_divider"
render :partial => "shared/note", :collection => @new_notes
render :partial => "broken", :status => 500
more: http://apidock.com/rails/ActionController/Base/render
# Extend ActiveRecord::Base with this method using your preferred technique.
def self.anaf_habtm(association, &block)
class_eval do
# Define a proc that will look up the (potentially) existing object
finder = proc {|id| association.to_s.singularize.camelize.constantize.where(:id=>id).first
}
# Define a proc that will set the association collection
set_collection = proc {|me, coll| me.send("#{association.to_s.tableize}=", coll)}
# Define the actual association setter.
define_method "#{association.to_s.tableize}_attributes=", lambda{|attributes_for_association|
coll = []
attributes_for_association.each_value do |params|
next if params["_destroy"] == "1"
obj = finder.call(params["id"]) if params.has_key?("id")
params.extend(HashExtension)
# ActiveRecord::Base.attributes=() doesn't like extra parameters.
coll << block.call(params.copy_without_destroy, obj)
end
set_collection.call(self, coll)
}
end
end
# Inside your model definition, define your association as such:
class Person < ActiveRecord::Base
has_and_belongs_to_many :web_sites, :autosave => :true, :uniq => true
has_and_belongs_to_many :recreational_organizations, :autosave => :true, :uniq => true
# This one has some extra parameters that will be saved to the association
anaf_habtm(:web_sites) do |params, web_site|
web_site = web_site ||= WebSite.find_by_url(params["url"])
web_site.attributes = params
web_site.save
web_site
end
# This one is more simple -- just make a new one if nil was passed in
anaf_habtm(:recreational_organizations) do |params, org|
org ||= RecreationalOrganization.new(:name => params["name"])
end
module HashExtension
def copy_without_destroy
a = {}
self.each {|key,val| a[key]=val unless key.to_s == "_destroy"}
a
end
end
include Rails.application.routes.url_helpers
# set host in default_url_options:
default_url_options[:host] = "localhost"
# can then use:
url_for()
# can check existing routes:
edit_user_url(User.first)
=> "http://localhost/user/1/edit"
class ErrorFormBuilder < ActionView::Helpers::FormBuilder
#Adds error message directly inline to a form label
#Accepts all the options normall passed to form.label as well as:
# :hide_errors - true if you don't want errors displayed on this label
# :additional_text - Will add additional text after the error message or after the label if no errors
def label(method, text = nil, options = {})
#Check to see if text for this label has been supplied and humanize the field name if not.
text = text || method.to_s.humanize
#Get a reference to the model object
object = @template.instance_variable_get("@#{@object_name}")
#Make sure we have an object and we're not told to hide errors for this label
unless object.nil? || options[:hide_errors]
#Check if there are any errors for this field in the model
errors = object.errors.on(method.to_sym)
if errors
#Generate the label using the text as well as the error message wrapped in a span with error class
text += " <span class=\"error\">#{errors.is_a?(Array) ? errors.first : errors}</span>"
end
end
#Add any additional text that might be needed on the label
text += " #{options[:additional_text]}" if options[:additional_text]
#Finally hand off to super to deal with the display of the label
super(method, text, options)
end
end
<%
# Seems to work for me. I just set the code to a variable.
@array = Model.all(:conditions => "condition_1 = true", :order => "name ASC", :limit => 10)
@random_object = @array[rand(@array.length)]
%>
def previous_post
self.class.first(:conditions => ["title < ?", title], :order => "title desc")
end
def next_post
self.class.first(:conditions => ["title > ?", title], :order => "title asc")
end
You can then link to those in the view.
<%= link_to("Previous Post", @post.previous_post) if @post.previous_post %>
<%= link_to("Next Post", @post.next_post) if @post.next_post %>