Chapter 4 Flashcards
true %>
build in rails function (stylesheet_link_tag) to include application.css for all media types (including computer screens and printers.
helper functions
creation of new rails functions
define a method full_title if no page title is defined (using provide on that page), then print out “Rails Tutorial Sample App”, otherwise add a | and precede it by the page title
module ApplicationHelper
# Returns the full title on a per-page basis def full_title(page_title = '') base_title = "Ruby on Rails Tutorial Sample App" if page_title.empty? base_title else page_title + " | " + base_title end end end
using full_title method, create a new title tag to use it:
steps to make home page with no custom page title
update home page to remove the provide function. update the test assert to test this
#
comments in ruby
string literal
zero or more characters grouped in quotes
concatenate two strings
“foo” + “bar”
“foobar”
interpolate a string and define meaning
first_name = “sam”
“#{first_name} Erd”
“Sam Erd”. interpolation is using a placeholderto insert a certain variable
printing a string
puts which appends a new line
nil
literally nothing
\n
new line
difference between ‘’ and “”
nothing, there identical, except ruby wont interpolate into single-quoted strings
is everything in ruby an object?
yes. even nil is an object.
what is an object?
object is a model of something with behavior and functions and attributes. place to store data about an entity.
empty?
method returns true or false
if s is nil, return “nil”, else if s is empty, return “empty”, else if, s includes “foo”, return “foo”
if s.nil? "nil" elsif s.empty? "empty" elsif s.include?("foo") "foo" else "lol" end
puts “empty” if x and y are empty, puts “one is empty” is x or y is empty, puts “x” if x is not empty
puts “xy” if neither x and y are empty
puts “empty” if x.empty? && y.empty?
puts “one is empty” if x.empty? || y.empty?
puts “x” if !x.empty?
puts “xy” if !x.empty? && y.empty?
puts two variables if neither is empty
puts “#{x} #{y}” if !x.empty? && !y.empty?
.to_s
convert virtually any object to a string.
nil.to_s
””
nil.empty?
error
nil.to_s.empty?
true
”“.nil?
false
nil.nil?
true
puts a string using interpolation unless its empty
puts “#{foo}” unless foo.empty?
!!nil
false
!!0
true
def string_message(str = '') returns whether string is empty or not. what is output for: string_message("foo") string_message("") string_message
string is nonempty
string is empty
string is empty
its possible to leave out the argument entirely because the code contains a default argument, which in ths case is the empty string
return string if its empty
return “empty” if str.empty?
last return in a function is unnecessary why?
returned regardless of return keyword
module ApplicationHelpter
gives us a way to package together related methods which can be then mixed in to Ruby classes using “include”
“foo bar yo” split this string into an array
“foo bar yo”.split
[“foo”, “bar”, “yo”]
split “fooxbarx” by the x’s
“fooxbarx”.split(“x”)
[“foo”, “bar”
get first, second, last elenment of an element
a. first
a. second
a. last
a.last == a[-1]
true
x = a.length
length of a string or could be array
a = [41, 8, 17] empty include 41 sort it reverse the order shuffle it
a. empty?
a. include?(41)
a. sort (can be used for strings too!)
a. reverse
a. shuffle
a.sort!
actually changes to array a unlike a.sort which just outputs a sorted array
push elements into array
x.push(6)
x
a = [42, 8, “foo”]
a.join
join using comma
“428foo”
a.join(‘, ‘)
“42, 8, foo”
0..9.to_a
undefined method for 9:fixnum
(0..9).to_a
gives array from 0 to 9, 10 elements
make a string array out of the words foo bar baz
and then show range of it
a = %w[foo bar baz]
a[0..2]
a = (0..9).to_a
return array from index 1 up to last index
a[1..-1]
range 1 through 5 and put our each number times 2
(1..5).each { |i| puts 2 * i}
or
(1..5).each do |i|
puts 2 * i
end
(1..5).each { |i| puts i}
each method passes range to block. |i| block variable. executes for each value in the range
puts “betelgeuse” three times
3.times {puts “betelgeuse” }
takes no variables
(1..5).map { |i| i ** 2 }
[1, 4, 9, 16, 25] produces new array
map out [a b c] into an array and change characters to uppercase or lower case
%w[a b c].map { |char| char.upcase(or char.downcase) }
map A B C into array and lower case it using symbol
%w[A B C].map(&:downcase)
test "should get home" do get :home assert_response :success assert_select "title", "Ruby on Rails Tutorial Sample App" end
do keyword that the body of the test is a block. test method takes in a string argument and a block, and then executes the body of the block as part of running the test suite.
user = {}
empty hash
user[“first_name”] = “michael”
key “first_name”, value “michael”
user[“first_name”]
returns value of key “first_name
create hash user with first name vampie in one line
name = { “first_name” => “vampie” }
in rails whats more common to use than strings as hask keys
symbols
symbol
looks like string but prefixed with colon. :name symbols dont contain value or objects, like variables. used as consistent name in a code. compared to String objects, its more efficient to use symbols.
current_situation = "good" creates string object and stores in memory current_situation = :good are only singe reference values only initialized once.
create hash with symbols
user = { :name => “f”, :email => “at” }
accessing undefined keys return what?
nil
create hash with special hash symbol
user = { name: “f”, email: “at” }
create nested hashes user with name and email
params[:user] = { name: “f”, email: “at” }
nested hashes are heavily used by rails
create each do for hash
hash.each do |key, value|
puts “key: #{key.inspect} has value #{value.inspect}”
end
inspect methdo
returns a string with a literal representation of the object
puts (1..5).to_a
1 2 3 4 5
puts (1..5).to_a.inspect
[1, 2, 3, 4, 5]
puts :name, :name.inspect
name
:name
puts “it\n”, “it\n”.inspect
it
“it\n”
stylesheet_link_tag ‘application’, media: ‘all’,
‘data-turbolinks-track’ => true
why no parenthesis?
in ruby, they are optional. there would be a parenthesis around it
when hashes are the last arguments to a function, the parenthesis are optional
stylesheet_link_tag ‘application’, media: ‘all’,
‘data-turbolinks-track’ => true
explain this now
calls the stylesheet_link_tag function with two arguments: a string, indicating the path to the stylesheet, and a hash with two elements, indicating the media type and telling Rails to use the turbolinks feature added in Rails 4.0.
data-track contains hyphens which are not allowed for symbols so we have to use the old syntax for it
s = String.new(“foobar”)
constructor to create string
a = Array.new([1, 2, 3])
array constructor
h = Hash.new(0)
(hash constructor) sets all nonexistent keys to return 0 instead of nil
s.class.superclass
string -> object -> basicObject -> nil
create class Word with method palindrom? that returns if a string in reverse is equal to the string forward
class Word def palindrome?(string) string == string.reverse end end
create palindrome method with class that inherits from string object
class Word
how can we add palindrome? to string class
class String
create palindrome? method
end
now every string object has palindrome? method
blank? method
specific to rails since its a rails extension
controller = StaticPagesController.new
create controller object
attr_accessor :name, :email
attr_accessor allows us to get and set @name and @email instance variables
def initialize(attributes = {}) @name = attributes[:name] @email = attributes[:email] end
empty hash. will return nil if there is no :name key and for :email.
def formatted_email "#{@name} " end
returns name
require ‘./example_user’
include ruby code into your session or code from a file in the current directory
we will see starting in chapter 7 that initializing objects using hash arguments, a technique known as mass assignment, is common in rails
true