Create a custom collection method

I am trying to create several methods for managing collections of objects.

I have the following instruction in the controller

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

In the configuration model, I have:

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

and in my lib folder I have a validation_rules file:

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

The idea is simple. The same model will require many configuration rules that I want to leave outside the controller and model (when I say a lot, I mean about 200).

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

How can I get rails to add this β€œregular” library of methods to the default Array arsenal?

To write, the above method is just a test, and not what I need to do, what the code does, this is not a problem, but Rails does not even look there before throwing an error.

Many thanks for your help!

+4
source share
1 answer

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

 module Enumerable def do_something self.each do |item| yield(item) end end end letters = ['a', 'b', 'c'] letters.do_something { |letter| p letter } 

My do_something method does nothing, in fact - a call is like a "everyone" call. But, of course, you can add your logic to it to achieve the desired result.

Keep in mind that everything that includes "Enumerable" will now have a do_something method, so this method must be encoded to play well with any type.

+4
source

Source: https://habr.com/ru/post/1337687/


All Articles