Sunday, January 27, 2008

Rails Lessons Learned the Hard Way

Things I've learned the hard way in Rails:
  • Layouts run inside views, not the other way round. Set an instance variable in app/views/monkeys/show.html.erb and it will be defined in app/views/layouts/monkey.html.erb but not vice versa.
    • set instance vars in view
      @foo_val = find_foo_val
    • pass variables to partials using
      <%= render :partial => "root/license", :locals => { :foo => @foo_val } -%>
    • use the instance var freely in the layout; it will take the value defined in the view
  • Dump an object for bobo debugging through the console or log:
    $stderr.puts tag_list.to_yaml
  • In a migration, if you define a unique index on an attribute, make sure both the index AND attribute are :unique => true, or else you'll get no uniqueness validation from Rails:
    
       create_table  :monkeys do |t|
         # set :unique here
         t.string :name, :default => "", :null => false, :unique => true
       end
       # if you have :unique here
       add_index :datasets, [:name], :name => :name,  :unique => true
    
  • If you scaffold a User or other object with private data, MAKE SURE you strip out fields you don't want a user setting or viewing:
    • Set attr_accessible, which controls data coming *in* -- prevents someone setting an attribute by stuffing in a form value.
    • In each view (.html.erb &c) and render method (to_xml), strip out fields you don't want anyone to see using the :only => [:ok_to_see, :this_too] parameter.
    • Set filter_parameter_logging, which controls what goes into your logs. (Logs should of course be outside the public purview, but 'Defense in Depth' is ever our creed.)
    Using the the restful-authentication generator as an example:
    • In the model, whitelist fields the user is allowed to set (this excludes things like confirmation code or usergroup):
      attr_accessible :login, :email, :password, :password_confirmation
    • In the controller file, whitelist only the fields you wish to xml serialize:
      format.xml { render :xml => @user.to_xml(:only => [:first_name, :last_name]) }
    • Obviously,In the show.html.erb and edit.html.erb strip out fields that shouldn't be seen.
    • In the model file, blacklist fields from the logs:
      filter_parameter_logging :password, :salt, "activation-code"
  • I won't even tell you how often this happens to me: If you edit or install code in a plugin, restart the server.

Labels: , , , , , , , , , , , , , , , ,

Parsing Names with Honorifics

In Railscast #16, Ryan Bates goes over Virtual Attributes in Rails, using the standard example of storing first and last names but getting/setting full names. He uses the following simple snippet:


def full_name=(name)
  split = name.split(' ', 2)
  self.first_name = split.first
  self.last_name = split.last
end

Which -- given that the focus was on virtual attributes -- is fine for explanation. However, that snippet will fail on names like "Franklin Delano Roosevelt" (last name of "Delano Roosevelt"). Here's a method which our 32d President will like better:


def clean(n, re = /\s+|[^[:alpha:]\-]/)
 return n.gsub(re, ' ').strip
end

# Returns [first_name, last_name] (or '' if there isn't any).
# Leading/trailing spaces ignored.
def first_last_from_name(n) 
    parts    = clean(n).split(' ')
    [parts.slice(0..-2).join(' '), parts.last]
end

names = [
    "Bill! Merkin,PhD.",
    "Jim               Thurston Howell III   ",
    "Charo", 
    "Heywood Jablowmie",
    "Sergei Rodriguez-Ivanoviv",
    "Polly Romanesq. ",
    "   ", 
    "",
    ]
p names.map { |n| first_last_from_name n }
# => [["Bill", "Merkin,PhD"], ["Jim Thurston Howell", "III"], ["", "Charo"], ["Heywood", "Jablowmie"], ["Sergei", "Rodriguez-Ivanoviv"], ["Polly", "Romanesq"], ["", nil], ["", nil]]

A regex is more extensible, and makes more sense for Perl refugees like me.


# Returns [first_name, last_name] (or nil if there isn't any).
# Leading/trailing spaces ignored.
def first_last_from_name_re(n)
    n = clean(n); 
    (n =~ / /) ? (n.scan(/(.*)\s+(\S+)$/).first) : [nil, n]     
end

p names.map { |n| first_last_from_name_re n }
# => [["Bill", "Merkin,PhD"], ["Jim Thurston Howell", "III"], [nil, "Charo"], ["Heywood", "Jablowmie"], ["Sergei", "Rodriguez-Ivanoviv"], ["Polly", "Romanesq"], [nil, ""], [nil, ""]]

However, as someone who can't check in at the automatic kiosks in airports because -- no joke -- the credit card thinks my last name is "IV", I like this version better.


# Returns [first_name, last_name, appendix] 
# (first name and appendix are nil if there isn't any).
# Leading/trailing spaces ignored.
# 
def first_last_appendix_from_name_re(n, appendix = nil)
    n = clean(n)
    appendix_re ||= %q((I|II|III|IV|(?:jr|sr|m\.?d|esq|Ph\.?D)\.?))
    if (n !~ / /) then
        [nil, n, nil]           # with no spaces return n as last name
    else
        n.scan(
          /\A(.*?)\s+           # everything up to the last name
           (\S+?)               # last name is last stretch of non-whitespace
           (?:                  # But! there may be an appendix.  Look for an optional group
             (?:,\s*|\s+)       #   that is set off by a comma or spaces
             #{appendix_re}     #   and that matches any of our standard honorifics.
             )?                 # but if not, don't worry about it.
           \Z/ix).first         # scan gives array of arrays; \A..\Z guarantees exactly one match
    end
end

p names.map { |n| first_last_appendix_from_name_re n }
# => [["Bill", "Merkin", "PhD"], ["Jim Thurston", "Howell", "III"], [nil, "Charo", nil], ["Heywood", "Jablowmie", nil], ["Sergei", "Rodriguez-Ivanoviv", nil], ["Polly", "Romanesq", nil], [nil, "", nil], [nil, "", nil]]

All three versions might make Japanese (and other "FamilyName GivenNames" cultures) sad.

Labels: , , , , , , , , , , , , ,