为集合创建自定义方法 [英] Creating custom method for collection

查看:61
本文介绍了为集合创建自定义方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建几种方法来操作对象集合.

I'm trying to create several methods to manipulate collections of objects.

我的控制器中有以下语句

I have the following statement in my controller

  def show
    @big = Configuration.find(params[:id]).elements
    @custombig = @big.getchanged
  end

在我的配置模型中:

require 'lib/validation_rules'
class Configuration < ActiveRecord::Base
  include ValidationRules

在我的 lib 文件夹中,我有一个名为 validation_rules 的文件:

and in my lib folder I have a file called validation_rules:

module ValidationRules
  def getchanged()
    names =[]
    self.each do |pp|
      names << pp.name
      return names
    end
  end
end

这个想法很简单.同一个模型会需要很多配置规则,我想把这些规则排除在控制器和模型之外(当我说很多的时候,我的意思是大约200).

The idea is simple. The same model will need a lot of configuration rules, which I want to keep out of the controller and the model (when I say a lot, i mean about 200).

上面代码的问题在于,当我调用它时,它告诉我该方法不存在,而这似乎是因为@big 是一组配置,而不仅仅是一个配置对象.当我在单个 Configuration 对象上尝试相同的方法时,它工作正常,但在这个版本中,它没有.

The problem with the code above is that when I call upon it, it tells me the method doesn't exist, and it seems this is happening because @big is an array of configurations, not just one configuration object. When I tried the same approach on a single Configuration object, it works fine, but in this version, it doesn't.

如何让 rails 将这个自定义"方法库添加到默认的 Array 库中?

How can I get rails to add this "custom" library of methods into the default Array arsenal?

为了记录,上面的方法只是一个测试,并不完全是我需要做的,代码所做的不是问题,但 Rails 在抛出错误之前甚至没有看那里.

For the record, the method above is just a test and not exactly what i need to do, what the code does is not the problem, but that Rails doesn't even look there before throwing the error.

非常感谢您的帮助!

推荐答案

您可以扩展 Enumerable 模块,该模块包含在 Array 等集合类中,并定义了诸如any?"之类的方法.和'收集'.例如:

You can extend the Enumerable module, which is included into collection classes such as Array, and which defines methods such as 'any?' and 'collect'. For example:

module Enumerable
  def do_something
    self.each do |item|
      yield(item)
    end
  end
end

letters = ['a', 'b', 'c']
letters.do_something { |letter| p letter }

我的 do_something 方法什么都不做,真的——调用它就像调用每个".但是当然您可以将您的逻辑添加到其中以实现所需的结果.

My do_something method does nothing, really -- calling it is like calling 'each'. But of course you can add your logic into it to achieve the desired result.

请记住,包括Enumerable"在内的任何内容现在都将具有 do_something 方法,因此应该对该方法进行编码以与任何类型完美配合.

Keep in mind that anything including 'Enumerable' will now have the do_something method, so that method should be coded to play nicely with any type.

这篇关于为集合创建自定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆