Rails 纠结的主谓宾方式写代码

linjunhalida · April 27, 2013 · Last by linjunhalida replied at April 27, 2013 · 1702 hits

为了一句话的好看,后面需要付出很多代价。现在是一个 rails 项目。model 有 user, idea,favorites:

Favorites.favorite user, idea

不好看。改成:

user.favorite idea

但是后面的代价是 user.rb 里面要有include AsFavoriter,然后加上一个as_favoriter.rb。 为了一行代码好看,把代码写得到处都是,是否值得呢?

Edit:又发现一种写法 (没有跑过):

class User
  def method_missing name, *args
    if name =~ /op_(.+)$/
      args.unshift self
      name.camelize.constantize.operate *args
    else
      super
    end
  end
end

class Favorite
  def self.operate user, item
    ..
  end
end

user.op_favorite idea

值得,你所谓的主谓宾方式,其实是更丑的那种...

http://ruby-china.org/topics/9013

让我想起 lisp 里面两种实现类的方法 (伪代码莫纠结):

(send :favorite idea user)
(send idea :favorite user)
You need to Sign in before reply, if you don't have an account, please Sign up first.