Sha256: e65a4f2e51d8a458aa47e86b1679d3b409ea1b33081789a3e1929d0e984e3ebc

Contents?: true

Size: 1.82 KB

Versions: 1

Compression:

Stored size: 1.82 KB

Contents

module FbGraph2
  module AttributeAssigner
    extend ActiveSupport::Concern

    included do
      extend ClassMethods
      attr_accessor :raw_attributes
      cattr_accessor :registered_attributes
    end

    module ClassMethods
      def register_attributes(attributes)
        self.registered_attributes = attributes
        send :attr_accessor, *attributes.values.flatten
      end
    end

    def assign(attributes)
      self.raw_attributes = attributes
      Array(self.class.registered_attributes).each do |type, keys|
        keys.each do |key|
          raw = attributes[key]
          if raw.present?
            value = case type
            when :raw
              raw
            when :date
              Date.strptime raw, '%m/%d/%Y' rescue raw
            when :time
              Time.parse raw
            when :timestamp
              Time.at raw
            when :application
              Application.new raw[:id], raw
            when :page
              Page.new raw[:id], raw
            when :pages
              Collection.new(raw).collect do |_raw_|
                Page.new _raw_[:id], _raw_
              end
            when :profile
              as_profile raw
            when :profiles
              Collection.new(raw).collect do |_raw_|
                as_profile _raw_
              end
            when :user
              User.new raw[:id], raw
            else
              # NOTE: handle these attributes in each class
              next
            end
            self.send :"#{key}=", value
          end
        end
      end
    end

    private

    def as_profile(raw)
      klass = if raw.include?(:namespace)
        Application
      elsif raw.include?(:category)
        Page
      else
        # TODO: needs to handle Event and Group here.
        User
      end
      klass.new raw[:id], raw
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
fb_graph2-0.0.1 lib/fb_graph2/attribute_assigner.rb