`
iandaicsu
  • 浏览: 52098 次
社区版块
存档分类
最新评论

Five Common Rails Mistakes

    博客分类:
  • Ruby
 
阅读更多

总结:

1  数据库需要Validation,也就是给migration添加(t.integer "user_id", :null =>false),以保证即使在代码有错误的情况下,数据库也不被污染

2  写面向对象的程序,而不仅仅是面向MVC的程序

3  使用Content_tag  helper method,让html更加干净

4  使用 find_each 代替 each [find_each uses find_in_batches to pull in 1000 records at a time, dramatically lowering the runtime memory requirements.] 

5  Code Review!

 

来源:http://www.mikeperham.com/2012/05/05/five-common-rails-mistakes/

I’ve worked with Rails for quite a while now and in that time I’ve seen a lot of Rails applications and both read and written a lot of bad Ruby code. Here’s five common mistakes that I see in almost every Rails codebase.

1. Migrations with no schema specifics

Your data model is the core of your application. Without schema constraints, your data will slowly corrode due to bugs in your codebase until you can’t depend on any fields being populated. Here’s a Contact schema:

  create_table "contacts" do |t|
    t.integer  "user_id"
    t.string   "name"
    t.string   "phone"
    t.string   "email"
  end

What is required? Presumably a Contact must belong_to a User and have a name — use database constraints to guarantee this. By adding :null => false, we ensure that the model is always consistent even if we have bugs in our validation because the database will not allow a model to be saved if it fails those constraints.

  create_table "contacts" do |t|
    t.integer  "user_id", :null => false
    t.string   "name", :null => false
    t.string   "phone"
    t.string   "email"
  end

Bonus points: use :limit => N to size your string columns appropriately. Strings default to 255 characters and phone probably doesn’t need to be that big, does it?

2. Object-Oriented Programming

Most Rails developers do not write object-oriented Ruby code. They write MVC-oriented Ruby code by putting models and controllers in the expected locations. Most will add utility modules with class-methods in lib/, but that’s it. It takes 2-3 years before developers realize: “Rails is just Ruby. I can create simple objects and compose them in ways that Rails does not explicitly endorse!”

Bonus points: introduce facades for any 3rd-party services you call. Provide a mock facade for use in your tests so that you don’t actually call the 3rd party service in your test suite.

3. Concatenating HTML in helpers

If you are creating helper methods, kudos, at least you trying to keep your view layer clean. But developers often don’t know the basics of creating tags within helpers, leading to messy string concatenation or interpolation:

str = "<li class='vehicle_list'> "
str += link_to("#{vehicle.title.upcase} Sale", show_all_styles_path(vehicle.id, vehicle.url_title))
str += " </li>"
str.html_safe

Yikes, it’s ugly and can easily lead to XSS security holes! content_tag is your friend.

content_tag :li, :class => 'vehicle_list' do
  link_to("#{vehicle.title.upcase} Sale", show_all_styles_path(vehicle.id, vehicle.url_title))
end

Bonus points: start introducing helper methods that take blocks. Nested blocks are a natural fit when generating nested HTML.

4. Giant queries loading everything into memory

You need to fix some data so you’ll just iterate through it all and fix it, right?

User.has_purchased(true).each do |customer|
  customer.grant_role(:customer)
end

You have an ecommerce site with a million customers. Let’s say each User object takes 500 bytes. This code will take 500MB of memory at runtime! Better:

User.has_purchased(true).find_each do |customer|
  customer.grant_role(:customer)
end

find_each uses find_in_batches to pull in 1000 records at a time, dramatically lowering the runtime memory requirements.

Bonus points: use update_all or raw SQL to perform the mass update. SQL takes time to learn well but the benefits are even more tremendous: you’ll see a 100x improvement in the performance.

5. Code review!

I’m guessing you are using GitHub and I’m also guessing you aren’t using pull requests. If you spend a day or two building a feature, do it on a branch and send a pull request. Your team will be able to review your code, offer suggestions for improvement and possible edge cases that you didn’t consider. I guarantee your code will be higher quality for it. We’ve switched to using pull requests for 90% of our changes at TheClymb and it’s been a 100% positive experience.

Bonus points: Don’t merge pull requests without tests for at least the happy path. Testing is invaluable to keep your application stable and your sleep peaceful.

分享到:
评论

相关推荐

    rails 2.3.2离线安装rails 2.3.2离线安装

    rails 2.3.2离线安装rails 2.3.2离线安装rails 2.3.2离线安装rails 2.3.2离线安装rails 2.3.2离线安装rails 2.3.2离线安装rails 2.3.2离线安装rails 2.3.2离线安装rails 2.3.2离线安装rails 2.3.2离线安装rails ...

    [Rails] Crafting Rails Applications (英文版)

    [Pragmatic Bookshelf] Crafting Rails Applications Expert Practices for Everyday Rails Development (E-Book) ☆ 图书概要:☆ Rails 3 is a huge step forward. You can now easily extend the framework, ...

    Ruby on Rails Guides v2 - Ruby on Rails 4.2.5

    Ruby on Rails Guides v2 - Ruby on Rails 4.2.5

    Ruby on Rails Tutorial

    《Ruby on Rails Tutorial》中文版(原书第2版,涵盖 Rails 4) Ruby 是一门很美的计算机语言,其设计原则就是“让编程人员快乐”。David Heinemeier Hansson 就是看重了这一点,才在开发 Rails 框架时选择了 Ruby...

    Rails项目源代码

    一个用Ruby on Rails搭建的图片分享的网站项目.完整源代码

    Rails之道,完整扫描版

    《Rails之道》按照Rails的各个子系统进行组织编排,分别介绍了Rails的环境、初始过程、配置和日志记录,Rails的分配器、控制器、页面生成和路由,REST、资源和Rails,ActiveRecord的基础、关联、验证和高级技巧,...

    rails敏捷开发的购物车系统

    本资源是参照rails敏捷开发第四版书中的例子,rails的版本是rails3.2.6

    Bootstrap for Rails (2015)

    Bootstrap 3 和 Rails 4(样例用的是Ruby 2.1.1,Rails 4.1.4) Table of Contents Preface 1 Chapter 1: Introducing Web Application Development in Rails 7 Why Bootstrap with Rails? 8 Setting up a Todo ...

    adminlte-rails, AdminLTE Rails gem 将AdminLTE主题与 Rails 资产管道集成.zip

    adminlte-rails, AdminLTE Rails gem 将AdminLTE主题与 Rails 资产管道集成 AdminLTE Rails gem AdminLTE 是后端的高级 Bootstrap 主题。英镑 AdminLTE Rails gem 与 Rails 资产管道集成了英镑AdminLTE主题。安装将...

    Ajax on Rails

    You'll learn to avoid user experience mistakes with proven design patterns. Beyond the how-to, Ajax on Rails helps you consider when Ajax is (and isn't) appropriate, and the trade-offs associated ...

    Rails101_by_rails4.0

    中文世界唯一一本Rails 4.0.0 + Ruby 2.0.0 的自學書籍

    使用Aptana+Rails开发Rails Web应用(中文)

    使用Aptana+Rails开发Rails Web应用 有Aptana的安装配置等等,中文

    rails api(文档)

    rails文档 rails api 英文

    Agile Web Development with Rails 4

    Ruby on Rails helps you produce high-quality, beautiful-looking web applications quickly. You concentrate on creating the application, and Rails takes care of the details., Tens of thousands of ...

    rails指南 中文版

    rails指南 中文版

    rails金典教材3本

    Ruby+on+Rails+3+Tutorial.pdf 应用Rails进行敏捷Web开发第4版.pdf (Agile Web Development with Rails) Rails.Recipes.Rails.3.Edition.pdf

    rails框架介绍分享

    介绍rails框架,版本是rails2点几的,不过思路差不多,具体区别可以去看官网

    rails2-sample

    rails2-sample good book

Global site tag (gtag.js) - Google Analytics