Rails 用 class_eval 动态定义 method,比 define_method 更易读

hjiangwen · October 29, 2020 · Last by monsterooo replied at December 29, 2020 · 384 hits

下面这段代码,has_one 通过下面的代码,生成以下 3 个 API

build_association(attributes = {})
create_association(attributes = {})
create_association!(attributes = {})

代码位置:https://github.com/rails/rails/blob/v4.2.10/activerecord/lib/active_record/associations/builder/singular_association.rb#L15

def self.define_constructors(mixin, name)
  mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
    def build_#{name}(*args, &block)
      association(:#{name}).build(*args, &block)
    end

    def create_#{name}(*args, &block)
      association(:#{name}).create(*args, &block)
    end

    def create_#{name}!(*args, &block)
      association(:#{name}).create!(*args, &block)
    end
  CODE
end
You need to Sign in before reply, if you don't have an account, please Sign up first.