Rails,帮助“!”

时间:2011-12-03 08:12:54

标签: ruby-on-rails-3.1

我经常写这样的东西:

def AModel < ActiveRecord::Base
  belongs_to :user

  def SomeCodeThatDoesSomeCalculations
    # some code here
  end

  def SomeCodeThatDoesSomeCalculations!
    self.SomeCodeThatDoesSomeCalculations
    self.save
  end
end

是否有更好的方法来生成带有后缀“!”的函数?

1 个答案:

答案 0 :(得分:1)

如果你经常这样做,你可以这样做:

class Model < ActiveRecord::Base

  def self.define_with_save(method_name)
    define_method "#{method_name}!" do
      send method_name
      save
    end
  end

  def save # stub method for test purpose
    puts 'saving...'
  end

  def do_stuff
    puts 'doing stuff...'
  end
  define_with_save :do_stuff

end

m = Model.new

m.do_stuff
# => 'doing stuff...'

m.do_stuff!
# => 'doing stuff...'
# => 'saving...'

如果你想在多个模型中使用它,你可能希望为包含这个define_with_save类方法的它们创建自己的基类,或者如果你确定的话可以将它添加到ActiveRecord::Base本身你需要它。

顺便说一下,我希望你不是用SomeCodeThatDoesSomeCalculations符号命名你的方法,因为它们通常被命名为some_code_that_does_some_calculations