【问题标题】:Ruby enumerable select with optional limit / find具有可选限制/查找的 Ruby 可枚举选择
【发布时间】:2017-06-19 14:40:37
【问题描述】:

我有以下可枚举来根据类别 (HAML) 选择文章

- blog( ENV[ "site" ] ).articles.select { | a | a.data[ :category ] == category }.each_with_index do | article, index |
= index

我希望能够限制此调用,但可以选择,即返回 2 或可能全部返回

- blog( ENV[ "site" ] ).articles.select { | a | a.data[ :category ] == category }.first( 2 ).each_with_index do | article, index |
= index

即引入first(2)

但不可能选择执行类似 first( 'all' ) 或 first( ) 的操作

谢谢

【问题讨论】:

  • 您不应该将这么多逻辑塞进您的视图中。您可以在模型上使用范围/方法来处理 select 部分,并使用助手来处理 first(2)/all 的条件逻辑。请注意,first('all') 没有意义,如果您想要 all,则只需省略 .first 调用即可。
  • @meagar 是对的。 blog(...) 是什么? articles 是 ActiveRecord 关系吗?可能有更简洁的方法来实现您想要的,而无需定义一个新方法。

标签: ruby haml middleman


【解决方案1】:
def some_meth(data, option)
  raise 'Invalid option' if !option.is_a?(Integer) || option != 'all'

  option == 'all' ? data : data.first(option)
end

用法:

- some_meth(blog( ENV[ "site" ] ).articles.select { | a | a.data[ :category ] == category }, 2)

- some_meth(blog( ENV[ "site" ] ).articles.select { | a | a.data[ :category ] == category }, 'all')

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 2015-06-16
    • 2014-06-25
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多