【问题标题】:Alternatives to using splat token with delegate in Rails 3.2.13 (Ruby 1.8.7)在 Rails 3.2.13 (Ruby 1.8.7) 中使用带有委托的 splat 令牌的替代方法
【发布时间】:2013-06-19 22:08:21
【问题描述】:

快速提问:我想delegate 一堆方法来关联我的模型:

z13u_methods = [
  :isbn_cleaned,
  :oclc_cleaned,
  :contents_cleaned, 
  :summary_cleaned,
  :title_statement,
  :is_serial?
]

delegate *z13u_methods, :to => :z13u, :prefix => true, :allow_nil => true

当我在 Ruby 1.9.3 上运行 Rails 3.2.13 时,这很好用。但是,当我在 Ruby 1.8.7 上运行 Rails 3.2.13(相同版本)时,遇到以下错误:

syntax error, unexpected tSYMBEG, expecting tAMPER
  delegate *z13u_methods, :to => :z13u, :prefix => true, ...

:to 突出显示的位置。

我猜在 Ruby 1.8 中,splatted 数组必须是最终参数(块名称除外)。有没有其他方法可以针对这种情况生成数组?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-1.8.7


    【解决方案1】:

    如果您只使用z13u_methods 进行delegate 调用,那么您可以这样做:

    delegate_args = [
      :isbn_cleaned,
      :oclc_cleaned,
      :contents_cleaned, 
      :summary_cleaned,
      :title_statement,
      :is_serial?,
      { :to => :z13u, :prefix => true, :allow_nil => true }
    ]
    delegate *delegate_args
    

    我认为这是您需要的基本模式。当然还有其他方法可以到达那里:

    delegate *(z13u_methods + [{ :to => :z13u, :prefix => true, :allow_nil => true }])
    
    # If you don't mind changing z13u_methods
    delegate *z13u_methods.push(:to => :z13u, :prefix => true, :allow_nil => true)
    
    # If you don't want to change z13u_methods
    delegate *z13u_methods.dup.push(:to => :z13u, :prefix => true, :allow_nil => true)
    # ---------------------^^^
    

    这个主题可能还有更多变体,这些只是我想到的几个选项。

    至于使用1.8.7,尽快升级,我认为1.8.7已经不支持了。

    【讨论】:

    • 谢谢,@mu。我会想出类似的东西:z13u_delegate_options = { :to => :z13u, :prefix => true, :allow_nil => true }; delegate *(z13u_methods << z13u_delegate_options),但我希望有一些“更干净”的东西。
    • <<push 相同。我不认为你会变得更干净,你可以将它包装在一个方法中,或者添加你自己的 delegate ,它会自行变平和飞溅。
    猜你喜欢
    • 1970-01-01
    • 2013-01-06
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    相关资源
    最近更新 更多