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?

1 Answer 1

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.