蕲春人 - 软件开发

简单就是美.

在Mac上使用gitX

gitX是mac上一个git的可视化工具,可以与gravatar\gist集成在一起。我比较喜欢它的界面形式,感觉很舒服。

安装方法:

最简单的安装方法就是下载它的二进制包,直接运行。 在它的wiki页面找到二进制包的下载地址,下载后,解压,直接运行,程序界面就出来了。

然后点菜单“GitX”中的’Enable Terminal Usage …’, 这样可以直接在命令行窗口中,在项目的根目录中直接运行gitx来启动gitX了。

My current project

更新

gitX官方的这个版本已经好久没有更新了,另外它也有一些缺点,如不能方便从文件中复制代码(很难选中代码的),我找到这个版本,它从原官方的版本更流行。另外它真的很好用,比官方的版本提高了很多功能点。你自己慢慢体会吧。

学习HTML5杂记

什么是 HTML5?

HTML5 将成为 HTML、XHTML 以及 HTML DOM 的新标准。 HTML 的上一个版本诞生于 1999 年。自从那以后,Web 世界已经经历了巨变。 HTML5 仍处于完善之中。然而,大部分现代浏览器已经具备了某些 HTML5 支持。

新特性

HTML5 中的一些有趣的新特性: + 用于绘画的 canvas 元素 + 用于媒介回放的 video 和 audio 元素 + 对本地离线存储的更好的支持 + 新的特殊内容元素,比如 article、footer、header、nav、section + 新的表单控件,比如 calendar、date、time、email、url、search

Video标签

参考资料

    <!DOCTYPE HTML>
<html>
<body>

<video width="320" height="240" controls="controls">
  <source src="movie.ogg" type="video/ogg">
  <source src="movie.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>

</body>
</html>
  

Audio标签

参考资料

    <!DOCTYPE HTML>
<html>
<body>

<audio controls="controls">
  <source src="song.ogg" type="audio/ogg">
  <source src="song.mp3" type="audio/mpeg">
Your browser does not support the audio tag.
</audio> 

</body>
</html>
  

Canvas元素

参考资料

HTML5 Web存储

参考资料

标签

属性

事件

Resources

将Rspec的测试任务添加到Rakefile中

写好Rspec测试好,一般是通过rspec spec/xxx_spec.rb这样来进行测试,这样不能批量进行多个spec文件的测试,解决方法是将rspec的测试任务添加了项目根目录中的Rakefile文件中去,以后直接执行rake或者rake spec就直接测试所有用例了。

1
2
3
4
5
6
7
8
9
10
require "rubygems"
require 'rake'
require 'rspec/core/rake_task'

task :default => :spec

RSpec::Core::RakeTask.new(:spec) do |t|
  t.pattern = Dir.glob('spec/**/*_spec.rb')
  t.rspec_opts = '--format progress -c'
end

Resources

初试Rails 3.1 Beta

看到消息 说Rails3.1 Beta出来了,我立刻就想试试,先从大体上了解一下看做了哪些改变。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
usermatoMacBook-Pro:code qichunren$ rvm use 1.9.2
Using /Users/qichunren/.rvm/gems/ruby-1.9.2-p0
usermatoMacBook-Pro:jjsc_web_backend qichunren$ gem install rails --pre
Successfully installed multi_json-1.0.1
Successfully installed activesupport-3.1.0.beta1
Successfully installed i18n-0.6.0beta1
Successfully installed activemodel-3.1.0.beta1
Successfully installed rack-1.3.0.beta
Successfully installed rack-cache-1.0.1
Successfully installed rack-test-0.6.0
Successfully installed rack-mount-0.7.2
Successfully installed hike-1.0.0
Successfully installed sprockets-2.0.0.beta.2
Successfully installed tzinfo-0.3.27
Successfully installed erubis-2.7.0
Successfully installed actionpack-3.1.0.beta1
Successfully installed arel-2.1.0
Successfully installed activerecord-3.1.0.beta1
Successfully installed activeresource-3.1.0.beta1
Successfully installed mail-2.3.0
Successfully installed actionmailer-3.1.0.beta1
Successfully installed rack-ssl-1.3.2
Successfully installed railties-3.1.0.beta1
Successfully installed rails-3.1.0.beta1
21 gems installed
Installing ri documentation for multi_json-1.0.1...
Building YARD (yri) index for multi_json-1.0.1...
Installing ri documentation for activesupport-3.1.0.beta1...
Building YARD (yri) index for activesupport-3.1.0.beta1...
Installing ri documentation for i18n-0.6.0beta1...
Building YARD (yri) index for i18n-0.6.0beta1...
Installing ri documentation for activemodel-3.1.0.beta1...
Building YARD (yri) index for activemodel-3.1.0.beta1...
Installing ri documentation for rack-1.3.0.beta...
Building YARD (yri) index for rack-1.3.0.beta...
Installing ri documentation for rack-cache-1.0.1...
Building YARD (yri) index for rack-cache-1.0.1...
Installing ri documentation for rack-test-0.6.0...
Building YARD (yri) index for rack-test-0.6.0...
Installing ri documentation for rack-mount-0.7.2...
Building YARD (yri) index for rack-mount-0.7.2...
Installing ri documentation for hike-1.0.0...
Building YARD (yri) index for hike-1.0.0...
Installing ri documentation for sprockets-2.0.0.beta.2...
Building YARD (yri) index for sprockets-2.0.0.beta.2...
Installing ri documentation for tzinfo-0.3.27...
Building YARD (yri) index for tzinfo-0.3.27...
Installing ri documentation for erubis-2.7.0...
Building YARD (yri) index for erubis-2.7.0...
Installing ri documentation for actionpack-3.1.0.beta1...
Building YARD (yri) index for actionpack-3.1.0.beta1...
Building YARD (yri) index for arel-2.1.0...
Installing ri documentation for activerecord-3.1.0.beta1...
Building YARD (yri) index for activerecord-3.1.0.beta1...
Installing ri documentation for activeresource-3.1.0.beta1...
Building YARD (yri) index for activeresource-3.1.0.beta1...
Installing ri documentation for mail-2.3.0...
Building YARD (yri) index for mail-2.3.0...
Installing ri documentation for actionmailer-3.1.0.beta1...
Building YARD (yri) index for actionmailer-3.1.0.beta1...
Installing ri documentation for rack-ssl-1.3.2...
Building YARD (yri) index for rack-ssl-1.3.2...
Installing ri documentation for railties-3.1.0.beta1...
Building YARD (yri) index for railties-3.1.0.beta1...
Installing ri documentation for rails-3.1.0.beta1...
file 'lib' not found
Building YARD (yri) index for rails-3.1.0.beta1...
Installing RDoc documentation for multi_json-1.0.1...
Installing RDoc documentation for activesupport-3.1.0.beta1...
Installing RDoc documentation for i18n-0.6.0beta1...
Installing RDoc documentation for activemodel-3.1.0.beta1...
Installing RDoc documentation for rack-1.3.0.beta...
Installing RDoc documentation for rack-cache-1.0.1...
Installing RDoc documentation for rack-test-0.6.0...
Installing RDoc documentation for rack-mount-0.7.2...
Installing RDoc documentation for hike-1.0.0...
Installing RDoc documentation for sprockets-2.0.0.beta.2...
Installing RDoc documentation for tzinfo-0.3.27...
Installing RDoc documentation for erubis-2.7.0...
Installing RDoc documentation for actionpack-3.1.0.beta1...
Installing RDoc documentation for activerecord-3.1.0.beta1...
Installing RDoc documentation for activeresource-3.1.0.beta1...
Installing RDoc documentation for mail-2.3.0...
Installing RDoc documentation for actionmailer-3.1.0.beta1...
Installing RDoc documentation for rack-ssl-1.3.2...
Installing RDoc documentation for railties-3.1.0.beta1...
Installing RDoc documentation for rails-3.1.0.beta1...
file 'lib' not found  
usermatoMacBook-Pro:code qichunren$ rails -v
Rails 3.1.0.beta1

看看rails命令有没有一些改动:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
usermatoMacBook-Pro:code qichunren$ rails --help
Usage:
  rails new APP_PATH [options]

Options:
  -r, [--ruby=PATH]              # Path to the Ruby binary of your choice
                                 # Default: /Users/qichunren/.rvm/rubies/ruby-1.9.2-p0/bin/ruby
  -b, [--builder=BUILDER]        # Path to a application builder (can be a filesystem path or URL)
  -m, [--template=TEMPLATE]      # Path to an application template (can be a filesystem path or URL)
      [--skip-gemfile]           # Don't create a Gemfile
  -G, [--skip-git]               # Skip Git ignores and keeps
  -O, [--skip-active-record]     # Skip Active Record files
  -d, [--database=DATABASE]      # Preconfigure for selected database (options: mysql/oracle/postgresql/sqlite3/frontbase/ibm_db/jdbcmysql/jdbcsqlite3/jdbcpostgresql)
                                 # Default: sqlite3
  -j, [--javascript=JAVASCRIPT]  # Preconfigure for selected JavaScript library
                                 # Default: jquery
  -J, [--skip-javascript]        # Skip JavaScript files
      [--dev]                    # Setup the application with Gemfile pointing to your Rails checkout
      [--edge]                   # Setup the application with Gemfile pointing to Rails repository
  -T, [--skip-test-unit]         # Skip Test::Unit files
      [--old-style-hash]         # Force using old style hash (:foo => 'bar') on Ruby >= 1.9

Runtime options:
  -f, [--force]    # Overwrite files that already exist
  -p, [--pretend]  # Run but do not make any changes
  -q, [--quiet]    # Supress status output
  -s, [--skip]     # Skip files that already exist

Rails options:
  -h, [--help]     # Show this help message and quit
  -v, [--version]  # Show Rails version number and quit

Description:
    The 'rails new' command creates a new Rails application with a default
    directory structure and configuration at the path you specify.

Example:
    rails new ~/Code/Ruby/weblog

    This generates a skeletal Rails installation in ~/Code/Ruby/weblog.
    See the README in the newly created application to get going.
usermatoMacBook-Pro:code qichunren$

继续建立一个新项目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
usermatoMacBook-Pro:code qichunren$ rails new rails3
      create  
      create  README
      create  Rakefile
      create  config.ru
      create  .gitignore
      create  Gemfile
      create  app
      create  app/assets/images/rails.png
      create  app/assets/javascripts/application.js
      create  app/assets/stylesheets/application.css
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/mailers
      create  app/models
      create  app/views/layouts/application.html.erb
      create  app/mailers/.gitkeep
      create  app/models/.gitkeep
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb
      create  config/environments
      create  config/environments/development.rb
      create  config/environments/production.rb
      create  config/environments/test.rb
      create  config/initializers
      create  config/initializers/backtrace_silencers.rb
      create  config/initializers/inflections.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/secret_token.rb
      create  config/initializers/session_store.rb
      create  config/initializers/wrap_parameters.rb
      create  config/locales
      create  config/locales/en.yml
      create  config/boot.rb
      create  config/database.yml
      create  db
      create  db/seeds.rb
      create  doc
      create  doc/README_FOR_APP
      create  lib
      create  lib/tasks
      create  lib/tasks/.gitkeep
      create  log
      create  log/.gitkeep
      create  public
      create  public/404.html
      create  public/422.html
      create  public/500.html
      create  public/favicon.ico
      create  public/index.html
      create  public/robots.txt
      create  script
      create  script/rails
      create  test/fixtures
      create  test/fixtures/.gitkeep
      create  test/functional
      create  test/functional/.gitkeep
      create  test/integration
      create  test/integration/.gitkeep
      create  test/unit
      create  test/unit/.gitkeep
      create  test/performance/browsing_test.rb
      create  test/test_helper.rb
      create  tmp/cache
      create  tmp/cache/.gitkeep
      create  vendor/assets/stylesheets
      create  vendor/assets/stylesheets/.gitkeep
      create  vendor/plugins
      create  vendor/plugins/.gitkeep
usermatoMacBook-Pro:code qichunren$ 

创建一个scaffold user后,发现在页面里/assets/application.js中包括了jQuery 1.6,还有rails.js for jquery这个。再也不需要之前的那个手工引入jQuery了,或者使用jquery-rails这个gem. 另外还生成有一个/assets/user.js.coffee文件,得要花时间学一下这个coffee-script了。

还发现一个有趣的现象,rails团队似乎偏爱json,在scaffold生成的代码中没有了以前的xml format

1
2
3
4
5
6
7
8
9

def index
  @users = User.all

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @users }
  end
end

另外多了一个assets的generator:

1
2
3
4
5
6
Example:
    `rails generate assets posts`

    Posts assets.
        Javascript:     app/assets/javascripts/posts.js
        Stylesheet:     app/assets/stylesheets/posts.css  

总体上看,变化不大,将jQuery,coffee_script,scss加入默认了。一切都继续演进。

使用feedzirra分析提取Feed

feedzirra 是一个很好用的提取和分析feed的工具。用法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
# encoding: utf-8
require "feedzirra"

def fetch_feed(feed_url)
  feed = Feedzirra::Feed.fetch_and_parse(feed_url)

  feed_entries = feed.entries
  feed_entries.each do |entry|
    puts entry.inspect
  end # end each
end

fetch_feed "http://tech.163.com/special/000944OI/kejitongxin.xml"

结果:

1
2
3
usermatoMacBook-Pro:gitcard qichunren$ ruby lib/blog_fetcher.rb 
#<Feedzirra::Parser::RSSEntry:0x00000102137858 @title="外媒分析称微软是黑莓和必应合作最大赢家", @url="http://tech.163.com/11/0504/16/737NSCOS000915BE.html", @summary="【赛迪网讯】5月4日消息,据国外媒体报道,在BlackBerry World上RIM请到一位令人意外的客座讲师——微软CEO史蒂夫-鲍尔默(Steve Ballmer)。鲍尔默在会上公开了与RIM的合作关系,称日后微软的Bing将代替谷歌成为黑莓移动设备上的默认搜索引擎。微软明显将从合作关系中获利,但RIM能够得到什么利益?鲍尔默表示,微软将对黑 ......", @published="2011-05-04 16:55:22">
#<Feedzirra::Parser::RSSEntry:0x0000010212e140 @title="工信部4月上半月发放241款电信设备进网许可证", @url="http://tech.163.com/11/0504/09/736SR7MQ000915BE.html", @summary="飞象网讯(崔玉贤/文)飞象网得知工信部4月份上半月发放了241款电信设备进网许可证,其中包含10款进网试用批文。 据悉,4月份上半月工信部共发放了TD终端22款,TD-SCDMA/GSM双模数字移动电话机15款,TD-SCDMA/GSM双模无线数据终端2款,TD-SCDMA固定无线终端5款。其中,TD-SCDMA/GSM双模数字移动电话机有5款进网试用批文,夏 ......", @published="2011-05-04 09:02:53">

在Rails项目中导出Excel

excel_rails 这个工具可以实现导出Excel数据的功能。它本身是基于ruby-spreadsheet

使用方法

  1. 安装 在Gemfile中
1
2
3
4
    # Excel
    gem 'excel_rails'
    # excel_rails need this
    gem 'spreadsheet'
1
bundle install  

  1. 使用 在控制器中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# encoding: utf-8
class RemitNotificationsController < ApplicationController
  def index
    @search = RemitNotification.valid.order("id DESC").search(params[:search])
    @remit_notifications = @search.paginate :per_page => 20, :page => params[:page]
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @remit_notifications }
      format.xls
    end
  end

end

在视图中

index.xls.rxls
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

# encoding: utf-8
excel_document(:filename => "all_lines.xls") do |workbook|
  sheet = workbook.create_worksheet
  sheet.name = "What's in a name"

  sheet.row(0).concat %w{汇款告知}

  # sheet[1,0] = 'Japan'
  # row = sheet.row(1)
  # row.push 'Creator of Ruby'
  # row.push 'Creator of rails'
  # row.unshift 'Yukihiro Matsumoto'
  # sheet.row(5).unshift 'HaHa'
  # sheet.row(3).push 'Charles Lowe', 'Author of the ruby-ole Library'
  # sheet.row(3).insert 1, 'Unknown'
  # sheet.update_row 4, 'Hannes Wyss', 'Switzerland', 'Author'

  sheet.row(1).replace [ '流水号', '客户名称','客户号','金额','通过认证时间','不通过时间','创建时间' ]

  sheet.row(0).height = 18
  sheet.row(0).height = 18

  format = Spreadsheet::Format.new :color => :blue,:weight => :bold,:size => 18

  sheet.row(0).default_format = format

  # 设置表格的标题栏为粗体
  bold = Spreadsheet::Format.new :weight => :bold,:horizontal_align => :center
  7.times do |x| sheet.row(1).set_format(x, bold) end

  @remit_notifications.each_with_index do |remite,index|
    sheet.row(index + 2).push remite.id,remite.user_name,remite.user_id,remite.money,date_format(remite.verified_at),date_format(remite.refused_at),date_format(remite.created_at)
  end
end

相关资源

使用Rails ERD生成数据库实体关系图

Rails ERD 可以生成数据库关系实体图,非常方便。

安装很方便,Rails ERD依赖Graphviz,所以首先需要安装Graphviz,在Mac下,直接

1
2
brew update
brew install cairo pango graphviz

然后在项目中的Gemfile中声明

1
2
3
group :development do
  gem "rails-erd"
end
1
2
bundle install        
rake erd    

这样,在项目的根目录中,就会生成一个名为ERD.pdf 文件

听《Sara》

Sara这首歌太好听了,虽然没有清楚具体是唱什么,但我感觉是讲一个故事,很好奇,我找到了歌词。

Sara 塞拉

鲍勃迪伦

I laid on a dune, I looked at the sky, When the children were babies and played on the beach. You came up behind me, I saw you go by, You were always so close and still within reach.

我躺在沙丘上,我向天空凝望, 那时孩子都还小,嬉戏在沙滩上。 我见你走来,又擦身而去 你就是如此接近,近到触手可及。

Sara, Sara, Whatever made you want to change your mind? Sara, Sara, So easy to look at, so hard to define.

塞拉,塞拉, 究竟是什么让你开始改变? 塞拉,塞拉, 一切看似简单,却难以细言。

I can still see them playin’ with their pails in the sand, They run to the water their buckets to fill. I can still see the shells fallin’ out of their hands As they follow each other back up the hill.

他们在沙堆提桶玩耍的情景依稀可见, 孩子们奔跑着把手中的水桶注满。 我还能看到正从他们手中滑落的贝壳, 排队退往沙丘的他们一个接着一个。

Sara, Sara, Sweet virgin angel, sweet love of my life, Sara, Sara, Radiant jewel, mystical wife. 塞拉,塞拉, 我此生的挚爱,可爱圣洁的天使, 塞拉,塞拉, 光彩照人的宝石,魔力四射的妻子。

Sleepin’ in the woods by a fire in the night, Drinkin’ white rum in a Portugal bar, Them playin’ leapfrog and hearin’ about Snow White, You in the marketplace in Savanna-la-Mar.

夜晚躺在篝火旁度过, 在葡萄牙酒馆把白朗姆酒斟酌, 他们玩着“跳背”游戏,聆听白雪公主的故事, 而你却在滨海萨凡纳的集市。

Sara, Sara, It’s all so clear, I could never forget, Sara, Sara, Lovin’ you is the one thing I’ll never regret.

塞拉,塞拉, 回忆如此清晰,我永不忘记, 塞拉,塞拉, 爱你之情我会终生不渝。

I can still hear the sounds of those Methodist bells, I’d taken the cure and had just gotten through, Stayin’ up for days in the Chelsea Hotel, Writin’ “Sad-Eyed Lady of the Lowlands” for you.

卫理公会圣钟之声我还能听见, 我已挺过难关,一切都已烟消云散, 在切尔西饭店没日没夜的这些天里, 写出了“忧伤眼神的低地女人”给你。

Sara, Sara, Wherever we travel we’re never apart. Sara, oh Sara, Beautiful lady, so dear to my heart.

塞拉,塞拉, 无论去哪我们从没分开。 塞拉,噢,塞拉, 美丽的女人,是我心上的爱。

How did I meet you? I don’t know. A messenger sent me in a tropical storm. You were there in the winter, moonlight on the snow And on Lily Pond Lane when the weather was warm.

我怎么遇见你?我不知道。 信使来时正逢一场热带风暴。 冬夜的你是白雪上的月光, 天暖时便是月光洒在了百合池旁。

Sara, oh Sara, Scorpio Sphinx in a calico dress, Sara, Sara, You must forgive me my unworthiness.

塞拉,噢,塞拉, 身着印花礼服的迷幻女王, 塞拉,塞拉, 我的卑微请你一定原谅。

Now the beach is deserted except for some kelp And a piece of an old ship that lies on the shore. You always responded when I needed your help, You gimme a map and a key to your door.

如今废弃的沙滩只剩几片水藻, 还有一艘破船在岸边停靠。 当我每每求助,你都会回应, 你会等在心门,给我方向给我指引。

Sara, oh Sara, Glamorous nymph with an arrow and bow, Sara, oh Sara, Don’t ever leave me, don’t ever go.

塞拉,噢,塞拉, 一身戎装的真命女神, 塞拉,塞拉, 别离开我,永远别走。

最近实践中学到的Rails测试技巧

最近花时间又将项目中的测试再次仔细地过了一遍。通过挖掘发现了几个提高测试效率的技巧,记一下。 不学习就要落后啊,Ruby的世界进化得太快了,测试技术也是如此。

  • FactoryGirl这个东西好用级了,之前虽然已经在项目中使用她了,但我之前还是没有完全挖掘出她的特性。对其中的association这个特性我是最喜欢了,让我完全不用关注关联记录的外键数据对应。想起曾经的Rails自带的Fixtures,还阵阵寒,那是给人给的东西么。当应用中的数据表关联多了,再加上业务功能多了,用Fixtures测试绝对会折磨死人,在不同的Fixtures文件中穿梭,人肉拼装适合各种业务场景的数据,那真费脑细胞。而FactoryGirl真的是用起来称心如意啊,她不是数据的fixture,她应该是作为一种数据的构建器(data builder),在测试中可以让你专注去构建 测试场景的数据和写测试断言。

  • 自动测试gem: autotest. 我和同事之前商量约定好,说提交代码前一定先在本地运行一遍rspec测试,然后再提交。这样工作得很好。我今天研究了一下autotest这东西,发现真是好东西啊。它可以检测到你改动了某个文件,然后就自动地为你执行一次这个文件关联的测试。这可好了,又省了不少事。

  • 接第二条,比起自动监测改动的文件自动测试,你还得关心测试的结果,更好的是有自动通知测试结果的好工具。mac下的 growl 就是这样一个工具。autotest-growl这样的一个Gem很好的做了这个事情。你再不不用切换到测试的终端窗口去查看测试结果,你只需要专心地写着代码,然后屏幕边上会自动显现一个半透明的提示框来告知测试结果(最喜欢看到就是一个绿宝石的提示框)。当然这个工具只有在Mac OSX上才有的。

  • 测试不是很快,这个也有解决方法。Spork就是这样的一个工具,它事先启动一个后端的DRB服务器(端口8989),加载Rails应用的环境。然后每次rspec的测试可以直接与spork打交道,省了加载Rails应用环境这个比较耗时的步骤,直接运行测试用例,速度飞快。

怎么样写好的ruby业务代码

标题很强,心中却很烦乱,写下这个解解闷,吐吐苦水。

最近与一个小Ruby程序员共事,交流起来还没有什么问题,可是看他写的代码,虽然坏不到哪里去,但我还是心里一阵阵反感,这和我平时阅读从github 上拉下的代码的感觉是完成不一样的。

给我不爽的地方有:首先他在用程序员的思维写业务代码。这一点虽然对程序的最终运行结果没有什么影响,但我是非常反感这一点。我一直对自己说,我要写可读的英语的,并且本身能说明它是要做什么事情的代码,尤其我是当在做电子商务方面的业务系统。

我们应该站在设计人员的角度来写代码。我们是整个系统的设计师,控制人员,管理人员,我们可以通过代码的方式为系统来设计各种业务规则。而不仅仅是为了用程序代码来码完业务操作。这种特点的典型特征就是在程序中(特别是在model 中)有很多这样的方法命名,如update_xxx, delete_xxx, set_x_to_y,这种类似的命名,它就是纯粹的数据操作,而不是用代码来表达业务!

都说程序要写耦合内聚什么的,模块化啦,抽取啦,减少重复,但是在这之间把握一个平衡还是要有很多磨练的。我之前一些时候在写Rails代码时就时常被这个问题折磨过,心里总是努力想把代码写得好一点,可最终完成业务目标时,看着自己的代码总是感觉不对劲.

不劲的地方有:

总是在考虑“我这段代码到底是单独抽出来呢,还是就这样放在其中呢”,“我感觉这个命名怎么那么别扭啊,哪里不对了?”等等之内的问题,然后花时间在这些代码段之间穿梭。其实我现在想明白了。要想让自己写的代码(我这里尤其是处理业务逻辑的代码)看得明白,读得顺畅,要把握好几点。

第一,要记得上面第一条中说到的。

第二,英语表达要不能太糟糕。 他英语不太过关,写的一些代码都是去google翻译查的,这我还是不说什么,可以有的翻译真的好离谱啊,再加上他自己的一些润色,完全可以我把搞迷糊。

第三点,要清楚业务需要的实质,明白什么是将来可能变化的,什么是肯定不变化的。明白了这一点,就知道一个业务操作中,到底是应该把方法怎么折分。不变的代码,就都写在一个方法中也是没有问题的,即实代码长一点,那样整个操作是一个整体,到时时候维护起来会很明了。

第四点,对于业务操作的方法,一般写得内聚紧凑一点很是没有什么问题的。不要惦记什么一个方法不能超过多少行代码的信条。

第五点就是测试了,这个一定得搞。