Posts Tagged ‘json’

fix to_json for methods ending with ‘?’

ruby methods are allowed to end with a ‘?’
while javascript Object properties are NOT.

This leads to problems when serializing a ruby
object to_json along with the :methods option
pointing to a method that ends with a ‘?’

# Example:
o.to_json(:methods => :valid?)
# returns something like
# { ..., "valid?": true, ... }

Workaround:

1)
Always access such a property with the [] operator.
Which actually is kind of weird because it’s not
really clear to me, wether this means that ‘?’
IS actually a valid porperty name in javascript
albeit one that just cannot be accessed in all
possible ways javascript syntax would allow it?

# >>> o = { "valid?": true }
# Object valid?=true
# >>> o["valid?"]
# true
# >>> o.valid?
# SyntaxError: syntax error

2)
try to workaround in rails’ to_json which leads
to a few problems (possible names clashing, only ruby=>json and not json=>ruby, …)

module ActiveRecord #:nodoc:
  module Serialization
    class Serializer #:nodoc:

      def serializable_record
        returning(serializable_record = {}) do
          serializable_names.each do |name|
            # ------------------------------------
            js_name = name.to_s.delete('?').to_sym
            serializable_record[js_name] = @record.send(name)
            # ------------------------------------
          end
          add_includes do |association, records, opts|
            if records.is_a?(Enumerable)
              serializable_record[association] = records.collect do |r|
                self.class.new(r, opts).serializable_record
              end
            else
              serializable_record[association] =
              self.class.new(records, opts).serializable_record
            end
          end
        end
      end

    end
  end
end

to_json in rails

user.to_json :include => :posts
user.to_json :only => [ :firstname, :lastname]
user.to_json :except => :password
user.to_json :methods => :errors

{}.to_json vs. OpenStruct.new({…

>> h = { :foo => "foo", :bar => 1 }
=> {:foo=>"foo", :bar=>1}
>> h.to_json
=> "{\"foo\": \"foo\", \"bar\": 1}"
>> require 'ostruct'
=> ["OpenStruct"]
>> o = OpenStruct.new(h)
=> #
>> o.to_json
=> “{\”table\”: {\”foo\”: \”foo\”, \”bar\”: 1}}”

# make it play nicely with to_json

>> class OpenStruct
>>   def to_json
>>     table.to_json
>>   end
>> end
=> nil
>> o = OpenStruct.new
=> #
>> o.foo = “foo”
=> “foo”
>> o.bar = 1
=> 1
>> o.to_json
=> “{\”foo\”: \”foo\”, \”bar\”: 1}”

lowpro autosave behavior to POST JSON

Event.addBehavior({
  '.autosave': Behavior.create({
    onchange : function() {
      var source = this.element;
      var name = source.name.split('['); // name according to rails convention
      var model = name[0]; // rails model name
      var resource = model + 's'; // rails resource (TODO better pluralization)
      var id = name[1].substring(0, name[1].length - 1); // rails model id

      var authToken = 'authenticity_token=' + $('auth-token').getValue()
      if(name[1].match(/new/)) {
        var url = '/' + resource + '?' + authToken
      } else {
        var url = '/' + resource + '/' + id + '?_method=put&' + authToken;
      }

      var inputs = $(source.parentNode).id.split('-');

      new Ajax.Request(url, {
        method: 'post',
        contentType: "application/json",
        postBody: Object.toJSON({
          survey_execution_id: $('survey_execution_id').getValue(),
          question_application_input_id: inputs[1],
          time_line_offset: inputs[2],
          value: source.getValue()
        })
      });
    }
  });
});