简体   繁体   中英

Conditional statement for a Serializer Rails 4

This is a really simple question, but I'm having trouble with the syntax. Rails 4, Ruby 2.

Have the following code working to serialize some records and dump them into geo json:

 module Serializers
  class GeoUser < ActiveModel::Serializer
    attributes :type, :geometry, :properties

    def type
      'Feature'
    end

    def geometry
        {
            type: 'Point',
            coordinates: [object.longitude, object.latitude]
        }
    end

    def properties
      {
        name: object.full_name,
        address: object.full_address,
        :'marker-color'  => object.marker_color,
        :'marker-symbol' => object.marker_symbol,
        :'marker-size'   => object.marker_size
      }
    end
  end
end

My problem is sometimes object.longitude, object.latitude are null/nil and I would like to set them to 0. Simple conditional statement, something like || 0, but I can't seem to get the syntax correct.

Suggestions, please :)

Thank you!

object.longitude || 0 object.longitude || 0 will work, as will object.longitude.to_f ( nil.to_f returns 0.0).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM