Vikram Singh Jadon Vikram Singh Jadon - 24 days ago 6
JSON Question

as_json dosen't support parameterized methods

While passing methods in 'as_json'/'to_json' to create json response of an object, we cannot pass parameters in methods. What is the reason behind it not being supported in 'as_json/to_json'

For example,

@posts.to_json(
:only => [:title, :body, :created_at, :tags, :category],
:methods => [:likes_count, :comments_count])
}


Here we cannot pass methods with arguments.

Answer

This is not supported out of the box, but we can build this.
For Rails 3.2. Add this in config/initializers/full_json.rb.

module ActiveModel
  module Serializers
    module JSON
      def as_full_json(options = nil)
        root = include_root_in_json
        root = options[:root] if options.try(:key?, :root)
        if root
          root = self.class.model_name.element if root == true
          { root => fully_serializable_hash(options) }
        else
          fully_serializable_hash(options)
        end
      end
    end
  end
end

module ActiveModel
  module Serialization
    def fully_serializable_hash(options = nil)
      options ||= {}

      attribute_names = attributes.keys.sort
      if only = options[:only]
        attribute_names &= Array.wrap(only).map(&:to_s)
      elsif except = options[:except]
        attribute_names -= Array.wrap(except).map(&:to_s)
      end

      hash = {}
      attribute_names.each { |n| hash[n] = read_attribute_for_serialization(n) }

      # These two lines do the magic. I check if it's Array, and in case it is, it should accept the arguments.
      method_names = Array.wrap(options[:methods]).select { |n| respond_to?(Array.wrap(n).first) }
      method_names.each { |n| n.is_a?(Array) ? (hash[n.first] = send(*n)) : (hash[n] = send(n)) }

      serializable_add_includes(options) do |association, records, opts|
        hash[association] = if records.is_a?(Enumerable)
                              records.map { |a| a.serializable_hash(opts) }
                            else
                              records.serializable_hash(opts)
                            end
      end

      hash
    end
  end
end

Try:

# Here method_with_arg is the method which accepts argument. 'arg' is the argument
@posts.as_full_json(
:only => [:title, :body, :created_at, :tags, :category],
:methods => [:likes_count, :comments_count, [:method_with_arg, 'arg']])
}.to_json

I'm sure this code can be cleaned and lessened. Possibly by use of alias-chain or something else. You can do it further. Let me know if this works for you.

Cheers