新手问题 Rails 的 delegate 的两个小问题,看了 apidock 后还是有点没明白

Catherine · 2016年03月21日 · 最后由 ruby_sky 回复于 2016年03月21日 · 3292 次阅读

1.通过 Foo.new.hello 打印出的 class 会是 Greeter 对象没错吧 主要没明白的是 prefix 的用法不是特别明白,意思就是若加上 prefix 在 Foo 的 delegate 里,调用 Foo.new.hello 时 prefix 的申明是放在哪里每次默认调用的?

class Greeter < ActiveRecord::Base
  def hello
    self.to_s + 'hello'
  end

  def goodbye
    self. + 'goodbye'
  end
end

class Foo < ActiveRecord::Base
  belongs_to :greeter
  delegate :hello, to: :greeter
end

Foo.new.hello   # => 
Foo.new.goodbye # => 
Person = Struct.new(:name, :address)

class Invoice < Struct.new(:client)
  delegate :name, :address, to: :client, prefix: true
end

john_doe = Person.new('John Doe', 'Vimmersvej 13')
invoice = Invoice.new(john_doe)
invoice.client_name    # => "John Doe"
invoice.client_address # => "Vimmersvej 13"

或者给 prefix 起别名:

class Invoice < Struct.new(:client)
  delegate :name, :address, to: :client, prefix: :customer
end

invoice = Invoice.new(john_doe)
invoice.customer_name    # => 'John Doe'
invoice.customer_address # => 'Vimmersvej 13'

API 文档上面很直观的写清楚了的呀,还是你没看完?

#1 楼 @huacnlee 额,谢谢!自己不仔细,没有看完,把"_"看成 ".",以为是默认的前缀方法.....

最终还是动态定义方法。

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