Ruby on rails 3.1 Rails,带有“的助手”&引用;

Ruby on rails 3.1 Rails,带有“的助手”&引用;,ruby-on-rails-3.1,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 defamodel“

我经常写这样的东西:

def AModel < ActiveRecord::Base
  belongs_to :user

  def SomeCodeThatDoesSomeCalculations
    # some code here
  end

  def SomeCodeThatDoesSomeCalculations!
    self.SomeCodeThatDoesSomeCalculations
    self.save
  end
end
defamodel

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

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

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...'
类模型“做事…”
m、 做点什么!
#=>“做事…”
#=>“保存…”
如果您希望在多个模型中使用该方法,您可能希望为它们创建自己的基类,其中包含此
define\u和\u save
class方法,或者如果您确定需要,您可以将其添加到
ActiveRecord::base
本身

顺便说一句,我希望你不是真的用
somecodethadoesmecalculations
符号来命名你的方法,因为它们通常被命名为
somecode\u doesculations