Ruby 一个重构代码的问题

robot_zhang · 2013年05月17日 · 最后由 robot_zhang 回复于 2013年05月20日 · 3611 次阅读

例如现有的代码如下:

class Product < ActiveRecord::Base
  attr_accessible :name
end

然后在很多的 views 中都使用了 product.name,某个时间,要对 name 进行统一的格式化,方案如下: 1.在 Product 中做一个额外的方法 2.在 helper 中做一个额外的方法 等等,但是 views 中的改动量都是巨大,非常别扭,有没有办法直接 hack Product 的 name 方法?

好像是用 alias 吧。重新定义 name

class Product
  # overwrite the product#name method
  def name
  end
end

@chenge 提醒了我,最终可以通过这种方式来:

class Product < ActiveRecord::Base
  attr_accessible :name
  def name
    undef name
    # the code for format name
  end
end

ps:这个方案会有问题,这个逻辑只会生效一次

最终我的办法如下谢谢 @chenge @leomayleomay

class Product < ActiveRecord::Base
  attr_accessible :name
  def name
    undef name
    self.name = # the code for format name
  end
end

这个方案会有问题,第一次是正确的,刷新页面后则无效果了,原因是在于我 undef 了 name 方法,所以还在找寻更好的方案中

@leomayleomay 这种 overwrite 会有递归调用的问题

alias old_name, name 估计可行

如果是 rails 的话 product model 加入

def name
    self[:name]
end

def name_with_option(option=false)
    if option
        #your code here
        "with option #{name_without_option}" #demo
    else
        name_without_option
    end
end
alias_method_chain :name, :option
class Product
  # overwrite the product#name method
  def name
    read_attribute(:name)
  end
end

奥,没留意楼主没用 ORM,那直接 2 楼行了

@fredwu draper 我试用了一下,对于代码侵入太多,导致分页,has_many 等关系什么的都需要重新配置,而且 controller 中也需要相应写很多 hack 代码,所以这个方案显得有点重了

ps: draper 蛮强大的一个 gem

@robot_zhangattr_accessor :name, 会有成员变量@name

class Product
  # overwrite the product#name method
  def name
    @name.foobarbaz
  end
end

@Rei 不好意思,我的错,我用了 activerecord 的。

@fredwu 非常感谢,也惭愧自己看文档不仔细,draper 是一个非常完美的解决这个问题的方案。

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