brighterplanet/charisma — Issue #2: awkward special handling of Numerics when encoding JSON
Author: seamusabshere
Created: 2011-10-11 15:00:02+00:00
State: open

in order to separate out units and properly encode numeric values into JSON i need hashes like this:

{ :carbon => { :value => 291092.22, :units => 'kilograms', :methodology => 'from_emissions_factor_blah_blah' } }

(note, among other things, no quotes around 291092.22 - it's a numeric)

i'm doing funky stuff like this...

def decisions
reports.inject({}) do |memo, report|
name = report.committee.name
characteristic = emitter_instance.characteristics[name]
value = characteristic.value
memo[name] = {
:value => value.is_a?(::Numeric) ? value : characteristic.to_s, # this is annoying because i'm subverting charisma...
:units => characteristic.units,
:methodology => report.quorum.name
}
memo
end
end

the immediate alternative is calling #to_s and not trying to separate out values and units. this is annoying because on the other end i have (and every other client library) would have to regex stuff

"291092.22 kg" =~ /([\d\.]+) ([\w]+)/
value = $1.to_f
units = $2.to_s