2

I am using an API and receiving a array of hashes. Lets say:

array = client.getObjects(123) //where 123 is some collection of object ID

I want to add some additional attributes to the array to use later in my view, like:

<%= array.getRequestor %> // return a string

What is the easiest way to do this? I was thinking about creating a new class that extends array but I wanted to know can I just add a string "requestor" attribute a lot easier?

Thanks

1
  • I don't think extending Array would be a good idea. What should be the result of [1, 2, 3, 4, 5, 6].getRequestor? Instead you could create a new class which only references your array. Commented Aug 29, 2015 at 11:25

2 Answers 2

2

Extending a core class is not a good idea in general, especially when the additional responsibilities you want to add in are specific to your functional domain.

6 months down the line, somebody (perhaps yourself) will be trying to debug the code and wondering why does Array expose a random custom method.

It would be better to explicitly define your custom view object, perhaps by using a Struct, eg:

# my_view_object.rb
class MyViewObject < Struct.new(:hash)
  def getRequestor
    # manipulate / return specific hash data
  end
end

# controller
@view_obj = MyViewObject.new(client.getObjects(123))

# view
@view_obj.hash # original hash
@view_obj.getRequestor # your custom attribute

Note that the intent of a Struct is to represent a custom data structure, not behaviour. If your custom method needs to do unrelated work, you might want to use a PORO (Plain Old Ruby Object) instead.

Sign up to request clarification or add additional context in comments.

Comments

0

I'd say that extending Array sounds like a really bad idea. I would suggest you instead wrap the array in hash of your own. For example

my_hash = {getRequestor: ?, array: array}

and then use it like

<%= my_hash.getRequestor %>

as in your example code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.