As_json for arrays?

Hi.

The file
/rails/activesupport/lib/active_support/json/encoders/enumerable.rb

Has:

class Array
(…)
def as_json(options = nil) #:nodoc:
self
end
end

I want a as_json method FooModel.all.as_json(:only => […]) that will
work same as FooModel.first.as_json(:only => […]).

I had to write my own method in a initializer:
class Array
def as_json_preserve_only_keys(preserve_keys)
self.collect do |el|
el.as_json(:only => preserve_keys)
end
end
end

Is there a better way to do this? Why does the Array method now look at
the “options” parameter?

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs