0

Ruby object has method/property:

def tentakles_count
  8
end

JavaScript object has key/property:

{ justEnough: true }

Now, when JavaScript gets serialised ruby object via XHR or WebSocket, developer has to use alien naming convention to access tentacles_count.

The same goes for Ruby, when it gets json object POSTed, developer has to use alien naming convention to access justEnough.

What would you do to deal with this little imperfection without going too crazy?

closed as primarily opinion-based by durron597, user40980, user22815, GlenH7, jwenting Jul 29 '15 at 7:53

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.

1

Ruby and its commonly used libraries and gems tend to blur the lines between method/property and key/property using attr_accessor, essentially giving an object both a property and getter/setter methods in one line. Either explicitly or implicitly, you'd have

def tentacles_count
  @tentacles_count
end

def tentacles_count=(n)
  @tentacles_count = n
end

def to_json
  # loop over all instance variables and convert them to json key-value pairs
end

(variables beginning with @ have object scope instead of method scope).

If it's not possible to do exactly this (say tentacles_count needs to dynamically count tentacles while you're in Ruby), to_json can be defined so as to include public methods as keys and their return values as values.

On the flip side, a json object parses most naturally into a Ruby Hash object (a dictionary). The syntax for accessing hashes is different from method notation (obj['justEnough']), but there are several library gems that will let you use the familiar convention if you really want to. I think the best pattern is to use the hash as an argument to an initializer: for example, OpenStruct.

Obviously there is no fully general answer to this question: there is, and of rights ought to be, awkwardness at the interface between different high-level languages. You can look at these little imperfections as a reminder to avoid tight coupling or duplicated logic between the different systems.

Not the answer you're looking for? Browse other questions tagged or ask your own question.