Skip to content

as_json chokes on invalid data #51

@pr1001

Description

@pr1001

While that doesn't exactly sound like a bad thing – it is being presented invalid data, after all! – I found the best way for one bad attribute not to take down everything was to monkeypatch the Json module:

module SimpleRecord::Json
  def as_json(options={})
    result = {
        'id' => self.id
    }
    result['json_class'] = self.class.name unless options && options[:exclude_json_class]
    defined_attributes_local.each_pair do |name, val|
      if val.type == :belongs_to
        result[name.to_s + "_id"] = get_attribute_sdb(name) rescue nil
      else
        result[name] = get_attribute(name) rescue nil
      end
    end
    result
  end
end

Perhaps this could be an option or just mentioned in the README if nothing else?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions