2

I have custom array methods like

class Array
  def decreasing?
    for i in (0...self.size)
      return false if self[i] > self[i+1]
    end
    true
  end

  def increasing?
    for i in (0...self.size)
      return false if self[i] < self[i+1]
    end
    true
  end
end

And

module Enumerable
  def sorted?
    each_cons(2).all? { |a, b| (a <=> b) <= 0 }
  end
end

Currently I have them in a model file randomly. Where is a better place to put these codes in Rails?

Jason Kim
  • 18,102
  • 13
  • 66
  • 105
  • possible duplicate of [Monkey Patching in Rails 3](http://stackoverflow.com/questions/3420680/monkey-patching-in-rails-3) – Mischa Mar 21 '13 at 08:21

2 Answers2

3

I would put it in an initializer (in config/initializers) called array_extensions.rb and enumerable_extensions.rb.

Mischa
  • 42,876
  • 8
  • 99
  • 111
  • Why do you think that it doesn't belong to ````/lib````? – Bob Mar 21 '13 at 08:28
  • @Bob, I am not saying that it doesn't belong there. You said "it must be", but it *does not have to be*, as my answer shows. If you put it in `/lib` you have to `require` it first with initializers that's not necessary. – Mischa Mar 21 '13 at 08:30
  • 1
    thanks) You can add ````lib```` to ```autoload_paths``` and it will be loaded) – Bob Mar 21 '13 at 08:34
  • Tested that both ways work, but using `config/initializers` was more convenient. – Jason Kim Mar 21 '13 at 17:44
1

I think it can be under /lib directory.

Bob
  • 2,081
  • 18
  • 25