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

simple css facts

div.A                           tag=div, class=”A”
div#A {set up a}       tag=div, id=”A”, only has effect a
div#A {set up b}      tag=div, id=”A”, now it has  both effects a and b if they donnot confilicts

#error-display li {

set up style xx

}  // any <li> element within the error-display will use style xx

render and redirect_to

def create

render :action=>new

end

it render the template new.html.erb, but the URL will be for the create action (use rake routes to find out the url of create action)

redirect_to :action=>new

it first call action new, and then render the template new.html.erb with the variables from the action new

+ and <<

The + operator is the normal concatenation choice, and is probably the fastest way to concatenate strings.

The difference between + and << is that + does not change the string itself, but << does

s = ‘a’
=> “a”
irb(main):002:0> s + ‘b’
=> “ab”
irb(main):003:0> s
=> “a”
irb(main):004:0> s < “ab”
irb(main):005:0> s
=> “ab”

Array:

?> a=[]
=> []
>> b=[1]
=> [1]
>> a+b
=> [1]
>> a
=> []
>> a<<b
=> [[1]]
>> a
=> [[1]] // array of arrays

// good to split a long string

>> “a,b”.to_a
=> [“a,b”]
>> “TruckRoute”.underscore
=> “truck_route”
>> str = “a\n b”
=> “a\n b”
>> str.to_a
=> [“a\n”, ” b”]

A simple way to test some validation

Ever write a code example like this?

1
2
3
4
5
6
7
describe Person do
  it "should validate presence of email" do
    person = Person.new(:email =>; nil)
    person.should_not be_valid
    person.should have(1).error_on(:email)
  end
end

That comes up pretty often in rails apps when spec’ing out models. There are a few matcher libraries out there like rspec-on-rails-matchers that provide matchers like this validate_presence_of(:email), which let you reduce the previous example to this:

1
2
3
4
5
describe Person do
  it "should validate presence email" do
    Person.new.should validate_presence_of(:email)
  end
end

Of course, the next step is to want to get rid of the redundancy between the docstring passed to #it and the matcher, so you end up with this:

1
2
3
4
5
describe Person do
  it do
    Person.new.should validate_presence_of(:email)
  end
end

Do it? Ugh! This has always driven me nuts when I see it do, so I’d make that this:

1
2
3
describe Person do
  it { Person.new.should validate_presence_of(:email) }
end

Well, thanks to a contribution from Joe Ferris from thoughtbot, we now have an implicit subject in our specs, so you can do this:

1
2
3
describe Person do
  it { should validate_presence_of(:email) }
end

w00t! Now that is concise. this feature hadn’t actually been released until rspec-1.1.12.

css overriding style

The easiest way to override CSS style declarations is to place that element inside a new container and define what it should appear like in that context. In this example, a paragraph with the class redOrNot will appear red everywhere except for when it’s placed inside an override element.

HTML Example:

1
2
<p class="redOrNot">This is red </p>
<span class="override"><p class="redOrNot">and this is not, even though it's the same class; This is blue</p></span>

CSS Example:

1
2
3
p.redOrNot { color: red }
.override p.redOrNot { color: blue }
My note: 1) if you don’t overriden the css style, it uses the default one from application.css;

2) if you override the same one,  (don’t know if there is an issue or not), just put the changed value, you don;t need to put the same name inside the container again. e.g.,

suppose this exists in application.css:

#errorExplanation { …}

you can define your own as

#errorExplanation { some changed value}

instead of

#errorExplanation {

#errorExplanation; // this is not needed

some changed values}

extend vs include

Include is for adding methods to an instance of a class and extend is for adding class methods. Let’s take a look at a small example.

module Foo
 def foo
 puts 'heyyyyoooo!'
 end
end

class Bar
 include Foo
end

Bar.new.foo # heyyyyoooo!
Bar.foo # NoMethodError: undefined method ‘foo’ for Bar:Class

class Baz
 extend Foo
end

Baz.foo # heyyyyoooo!
Baz.new.foo # NoMethodError: undefined method ‘foo’ for #<Baz:0x1e708>

As you can see, include makes the foo method available to an instance of a class and extend makes the foo method available to the class itself.

A Common Idiom

Even though include is for adding instance methods, a common idiom you’ll see in Ruby is to use include to append both class and instance methods. The reason for this is that include has a self.included hook you can use to modify the class that is including a module and, to my knowledge, extend does not have a hook. It’s highly debatable, but often used so I figured I would mention it. Let’s look at an example.

module Foo
 def self.included(base)
 base.extend(ClassMethods)
 end
 
 module ClassMethods
 def bar
 puts 'class method'
 end
 end
 
 def foo
 puts 'instance method'
 end
end

class Baz
 include Foo
end

Baz.bar # class method
Baz.new.foo # instance method
Baz.foo # NoMethodError: undefined method ‘foo’ for Baz:Class
Baz.new.bar # NoMethodError: undefined method ‘bar’ for #<Baz:0x1e3d4>

There are a ton of projects that use this idiom, including Rails, DataMapper, HTTParty, and HappyMapper.