Mock

let(:user) { mock_model(User) }
works

it “should mock a user” do
@user = mock_model(User)
end
works

before(:all) do
@user = mock_model(user)
end
fails

before(:each) block { a=mock(User)
works

Mocks are implicitly verified and cleared out after(:each) so they won’t work in before(:all).

mock doesnot work in an example group (describe() block), but it works in an example (it() block).

update attribute

def name=(name)
write_attribute(:name, name.capitalize)
end

def name
read_attribute(:name).downcase # No test for nil?
end

Image what will happen if you don’t use read_attribute or write_attribute

def name
name.upcase
end
=!= booom, infinite loops, think it about why

idiomatic adj.  [idi] didaode, fuheyuyanxiguan de

 

 

add new columns in csv file

Psudo code:

FasterCSV.parse(file, parse_options) do |row|
// hanle header
if header
row.push(“new col”)
next
end
// handle the column value of the “new column”
row.push(“column_value”)
end

push(*args)

A shortcut for appending multiple fields. Equivalent to:

args.each { |arg| faster_csv_row << arg }

This method returns the row for chaining.

[Source]

# File lib/faster_csv.rb, line 253
def push(*args)
args.each { |arg| self << arg }

self # for chaining
end

file format

C:\> copy con lala.txt
a
file
with
many
lines
^Z

C:\> irb
irb(main):001:0> text = File.open('lala.txt').read
=> "a\nfile\nwith\nmany\nlines\n"
irb(main):002:0> bin = File.open('lala.txt', 'rb').read
=> "a\r\nfile\r\nwith\r\nmany\r\nlines\r\n"

"    hello    ".strip   #=> "hello"   
"\tgoodbye\r\n".strip   #=> "goodbye"
remove leading and trailing whitespace

\r carriage return
\n field line

symbol

MY_CONSTANT = “abcdeeeedfjeouwpuo”

too long to compare to check if a string equal to MY_CONSTANT

Use symbol:
MY_CONSTANT = :string

symbol having an object identifier; that’s the reason of a O(1) comparison between symbols

symbol is just something fixed, not a string. When you need to use it, use :sym, not “sym”.

communication between input and attribute

user input something simple to write
attributes in db use some complicated name to easy understand

several ways to solve this translation between user input and db objects
1) interpret user input to db objects at the level of user input leavel, maybe a name mapping?
2) update the attributes in the rails model
def attribute=(val)
pp = case val.ucase
when ‘F’ then ‘female’
when ‘M’ then ‘male’
else val
end
write_attribute(:attribute, pp)
end

render partials

render(:partial => article, : object => @new_article)
1) the :partial value does not have a prefix underscore; even the file name does
:partial => shared/header
look for app/views/shared/_header.html.erb
2) the value of : object is @new_article, and this value is assgined to the local variable in the partial with the same name as the template, which, here, is article;
so you can use article.title in the partial temple, which has the same value as @new_article.title