Skip to content

Using with ActiveRecord

levent edited this page May 21, 2012 · 2 revisions

Example with ActiveRecord

    class Datastream < ActiveRecord::Base
      belongs_to :feed
    end

    class Feed < ActiveRecord::Base
      has_many :datastreams
      extend Cosm::Base
      is_cosm :feed
    end

Provided methods

    @cosm_feed = feed.to_cosm # returns an instance of Cosm::Feed
    @cosm_feed.to_json(:version => "1.0.0") # converts your feed and associated datastreams into Cosm V2 JSON
    @cosm_feed.as_json(:version => "0.6-alpha") # provides a json hash for 0.6-alpha
    @cosm_feed.to_xml(:version => "0.5.1") # converts your feed and associated datastreams into Cosm V2 XML (EEML)

Supported formats

  • JSON "1.0.0" - used by Cosm API v2
  • JSON "0.6-alpha" - used by Cosm API v1
  • XML "0.5.1" - used by Cosm API v2
  • XML "5" - used by Cosm API v1
  • CSV v1 - used by Cosm API v1
  • CSV v2 - used by Cosm API v2

Mapped fields

See [the Cosm Api docs] 1 for a description of each field.

By default the gem expects your object to have the following fields:

Feeds

  • creator
  • datastreams
  • description
  • email
  • feed
  • icon
  • id
  • location_disposition
  • location_domain
  • location_ele
  • location_exposure
  • location_lat
  • location_lon
  • location_name
  • private
  • status
  • tags
  • title
  • updated
  • website

Datastreams

  • current_value
  • datapoints
  • feed_creator
  • feed_id
  • id
  • max_value
  • min_value
  • tags
  • unit_label
  • unit_symbol
  • unit_type
  • updated

Datapoints

  • at
  • value
  • feed_id
  • datastream_id

If you use different field names, want to map custom fields or want to map fields onto instance methods you can:

    class Feed < ActiveRecord::Base
      extend Cosm::Base

      has_one :geo_location
      is_cosm :feed, {:location_lat => :geo_lat, :location_lon => :geo_lon}


      def geo_lat
        geo_location.try(:latitude)
      end

      def geo_lon
        geo_location.try(:longitude)
      end
    end