Ruby on Rails: links

The official format is:

link_to(name, options={}, html_options={})

In the templates, you can use it as:

<%= link_to “Home”,    ‘home_path’ %>

Everywhere else (example):

link_to 'New', {controller: 'articles', action: 'new'}, {class: 'large'}

First argument: The text that will show as part of the link

Second argument: the name of the route we are invoking

Third argument: options, anything else you need to pass to the links

You can also encapsulate a bunch of DOM elements with it:

<%= link_to new_project_path do %>
  More DOM elements and / or text in here
<% end %>

Ruby 101: The basics

To play with ruby in a system where it is installed, just type “irb”

Comments

=begin

Commenting out several lines (make sure =begin and =end are not indented)

=end

Strings and sub strings:

# Return a boolean base of substring found:

somestr.include? “somesubstr”

# Doing a search and replace regular expression (look for the letter y, change it to x):

somestring.gsub!(/y/, “x”)

“foo” + “bar” # String concatenation

“#{first_name} Hartl” # String variables interpolation

puts something  # print variable something

mystr.empty? # Check if mystr is empty

nil.to_s  # Will print “”, it cast to string

mystr.nil? # Test if mystr is null

puts “The string ‘#{string}’ is nonempty.” unless string.empty? // Print if not empty

"Toronto - Canada".downcase # Downcase stuff
"New York, USA".upcase # Upcase stuff
"HELLO".capitalize # Capitalize stuff

"a string".methods # If you want to see all other methods off the string class

"a string".methods.grep /case/ # even better, you can search them!

Playing with dates

'Now is #{Time.now}' // Prints the current machine's time
'Now is #{Time.now.year}' // Prints just the year part of the current time

if statements

if 1 < 2

print “I’m getting printed because one is less than two!”

elsif

print “something else”

else

print “the default”

end

# You can also use unless. If the expression is false (as oppose to true in if), the thing gets evaluated:

unless 1 > 2

print “This is an impossibility”

end

 

Methods in Ruby:

def string_message(string)
return “It’s an empty string!” if string.empty?
return “The string is nonempty.”
end

The return is implicit in the last line executed

Arrays:

a = “fooxbarxbazx”.split(‘x’) // Split into an array a using ‘x’, the opposite is a.join(‘x’)

a = [42, 8, 17]

a[-1] // Negative indexes start reading from the last element

a.first // First element, you can also use .second or .last

b = a.sort / a.reverse / a.shuffle // As their name indicate

a.sort! // this means apply the changes to a

(0..9).to_a // Produces an array with element from range 0 to 9. If you use three dots, the last number is not included

a = %w[foo bar baz quux] // Produces [“foo”,”baz”,”quux”]

a[0..1] // From the array above, produces a[“foo”, “baz”]

Blocks:

(1..5).each { |i| puts 2 * i } // Inputs 2, 4, 6, 8, 10

You can also have multi-line blocks:

(1..5).each do |number|

puts 2 * number

puts ‘–‘

end

each_with_index do |item, index| allows you to use the index inside the loop

3.times { puts “Betelgeuse!” } // Do something several times

a = (1..5).map { |i| i**2 } // Multipy numbers 1 to 5  to the power of two, and produce an array with the results

For loops:

for num in 1..20

puts num

end

Another kind of loop, with next and break statements:

i = 20 loop do

# Skipping odd numbers:

i -= 1 next if i % 2 == 0

print “#{i}”
break if i <= 0

end

Hashes:

user = { “first_name” => “Michael”, “last_name” => “Hartl” }

You can also use symbols, which are just strings with no quotes, to represent the above:

user = { :first_name => “Michael”, :last_name => “Hartl” }

user[:name] =  user[“name”]

Printing hash values:

flash = { success: “It worked!”, error: “It failed.” }
flash.each do |key, value|
puts “Key #{key.inspect} has value #{value.inspect}”
end

The above will print:
Key :success has value “It worked!”
Key :error has value “It failed.”

Try / Catch statements in Ruby:

begin
# Something that may go wrong here
rescue Exception=>e
# Something did go wrong…
end

Getting user’s input:
gets.chomp

Accessing instances class variables (useful for testing):

my_instance = new SomeObject
my_instance.instance_variable_get(:@some_variable)

Ruby On Rails: Server side validation

It happens inside the model. All you have to do is:

class Micropost < ActiveRecord::Base
attr_accessible :content, :user_id
validates :content, :length => { :maximum => 140 }
end

Rails 4.0

validates_presence_of :title, :body # make sure you have that field
validates_uniqueness_of :email # Makes sure your email is unique across the system
validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id] # Validates that the teacher_id is unique for a semester and class
validates_length_of :email, :within => 5..50 # validates a length range
# validate the actual format via regular expressions:
validates_format_of :email, :with =>  /^[^@][w.-]+@[w.-]+[.][a-z]{2,4}$/i

You can also add your own, custom validation methods, as follows:

validate :article_should_be_published

  def article_should_be_published
    errors.add(:article_id, "is not published yet") if article && !article.published?
  end

Apache: setup reverse proxy

Useful for situations where you need to hit APIs from websites that are not part of your domain, and you’d like to avoid the cross scripting limitations of JS without using jsonp

go at the top level of the config:
ProxyRequests On
ProxyVia On
Then setup the URL redirection:
proxyPass /adapter/ http://thefinaldestinationhere/evenwith/subdirectories
proxyPassReverse /adapter/ http://thefinaldestinationhere/evenwith/subdirectories
This is what my config currently looks like
ProxyRequests On
ProxyVia On
<VirtualHost *:80>
    DocumentRoot “/your/root/dir/here”
    ServerName local.admin.dev
    proxyPass /adapter/  http://thefinaldestinationhere/evenwith/subdirectories
    proxyPassReverse /adapter/ http://thefinaldestinationhere/evenwith/subdirectories
</VirtualHost>