Rails, Part 2

Quick review of Product ‘crud’

Magic

class MyClass
  def say_hello()
    puts "Hello!"
  end
end

o = MyClass.new

o.say_hello
# o.do_something  # <=== no such method.

new_method_name = 'do_something'
MyClass.define_method(new_method_name) {
  puts "Running the new method"
}

o.do_something

Validation

validates :title, :description, :image_url, presence: ​​true
validates :title, uniqueness: ​​true
validates :image_url, allow_blank: ​​true, format: {
  with:    ​​%r{​​\.​​(gif|jpg|png)​​\z​​}i,
  message: ​​'must be a URL for GIF, JPG or PNG image.'
}
validates :price, numericality: { greater_than_or_equal_to: 0.01 }

Unit tests

 	test "product attributes must not be empty" do
​ 	  product = Product.new
​ 	  assert product.invalid?
​ 	  assert product.errors[:title].any?
​ 	  assert product.errors[:description].any?
​ 	  assert product.errors[:price].any?
​ 	  assert product.errors[:image_url].any?
​ 	end

Or to be more specific

 	test "product price must be positive" do
 	  product = Product.new(title:       ​​"My Book Title",
 	                        description: ​​"yyy",
 	                        image_url:   ​​"zzz.jpg")
 	  product.price = -1
 	  assert product.invalid?
 	  assert_equal ["must be greater than or equal to 0.01"],
 	    product.errors[:price]

Fixtures

​ 	one:
​ 	  title: ​MyString​
​ 	  description: ​MyText​
     image_url: ​lorem.jpg​
​ 	  price: ​9.99​
	
​ 	two:
​ 	  title: ​MyString​
​ 	  description: ​MyText​
     image_url: ​lorem.jpg​
​ 	  price: ​9.99

Store controller

Yield in Ruby

def my_map(array)
    i = 0
    answer = []
    while i < array.count
        answer << yield(array[i])
        i += 1
    end
    answer
end

squares = my_map([8, 6, 7, 5, 3, 0, 9]) {|n| n*n}
puts(squares)

Layout

Cookies / Sessions

Make a cart

Error handling