0

I currently need to pass some methods as parameters in order to render json properly:

render json: @objects.to_json(methods: [:num_of_properties])

This syntax currently works. However, there is another method I want to pass; this method takes in 1 argument.

I figured this would work:

render json: @objects.to_json(methods: [:num_of_properties, :property_is_owned_by?(current_user)])

This does not work. Is this even possible to do? I figured that if you can pass methods as arguments in the first place, you must be able to pass methods that take in arguments. But I don't know. I'm not too familiar with Ruby.

Angel Garcia
  • 1,547
  • 1
  • 16
  • 37

1 Answers1

1

echnically its not intended to give arguments to_json only takes getters. But you could do something along those lines:

class ObjectClassOfYourChoice
  attr_accessor :current_user

  def property_is_owned_by?(user = nil)
    user ||= current_user
    # rest of your code
  end
end


@objects.each do |object|
  object.current_user = current_user
end
render json: @objects.to_json(methods: [:property_is_owned_by?]

Although I wouldn't do it like this since you have to set for all the object and thats just codesmell.

Denny Mueller
  • 3,505
  • 5
  • 36
  • 67
  • works perfectly, thanks! – Angel Garcia Jul 17 '18 at 18:21
  • thanks @engineersmnky for reminding me of my typo in the method arguments and alleging me of copying an answer. I renamed the class to something way more suitable since anybody who reads this can't see that I called is `Object` because OP called his var `@objects`. – Denny Mueller Jul 18 '18 at 07:50