Rails 屌丝版的 annotate

marssun · 2015年04月03日 · 最后由 mingyuan0715 回复于 2015年04月04日 · 2235 次阅读

annotate 介绍

annotate 是一个文档类的 gem,可以在 model 中以注释的方式插入到文件中。实际的效果如下图所示: 在 model 注释了表名、字段名、字段类型和约束。在团队开发的时候可能会涉及多人对一个 model 进行了多次编辑,容易造成团队中的人员对这个 model 的结构理解混乱。在开发的时候引入这个 gem 可以将 model 的表结构清晰的展现在 model 文件中有利于开发人员理解。不仅如此,annotate 注释 tests, fixtures, factories。

使用方式

  • annotate 默认注释 models, tests, fixtures, factories: shell cd /path/to/app annotate
  • 仅注释 model: shell annotate --exclude tests,fixtures,factories,serializers
  • 注释路由: shell annotate --routes
  • 删除 model/test/fixture/factory/serializer 里的注释: shell annotate --delete # 屌丝版 annotate 因为感觉用不到 annotate 其他的功能只要在 model 里添加注释就可以了,所以就以 rake 的方式做了一个屌丝版的 annotate 步骤如下: 1.编写一个 rake 接受类名作为参数取到对应的类: ruby namespace :model do task :db_structure, [:klass] => :environment do |t, args| klass = Class.const_get(args[:klass]) end end 2.取到类的数据库列表信息 ruby columns = klass.columns 3.在 columns 就可以拿到想要的信息了示例如下 ruby c = columns.first c.name c.type c.sql_type c.null c.default c.limit c.primary 4.依靠约定找到对应的文件 ruby file = File.expand_path klass.to_s.underscore + ".rb", Rails.root.to_s + "/app/models/" 5.格式化输出 ruby # @length : 字段长度 # @name:字段 "%-#{@length.to_s}s%2s" % [@name, ""] 6.打开文件插入内容 ruby #@file : 文件路径 #@data_table : 将格式化好的列整合到一个数组中 File.open(@file, "a+") do |f| content = f.readlines `> #{@file}` content.insert(@data_table) content.flatten! content.each do |s| f.write s end end 主要的内容就是上面这些,在编写 rake 的时候感觉很无力的就是,感觉 rake 是破坏面向对象的重灾区,有时候想编写一些类到 rake 文件中,但是感觉又不太合适。。。哎,到底要把 rake 中需要的类写在哪呢?

cto 教的:把 rake 看成 controller

#1 楼 @mingyuan0715 有些类跟系统业务相关性差得太多,写在 models 里又不太合适。。。

#2 楼 @marssun 不一定写在 models 里啊,可以单独写一个 class 或者 module,这样好测试,容易复用。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号