Sha256: 6c3805f56f19056f6ccd2cde2cc3619ecabc0618ef2a7911d0ef10e6465edc7a

Contents?: true

Size: 1.82 KB

Versions: 7

Compression:

Stored size: 1.82 KB

Contents

module EY
  class CloudClient
    class ApiStruct < Struct
      def self.new(*args, &block)
        args = [:api] | args
        super(*args) do |*block_args|
          block.call(*block_args) if block

          def self.from_array(api, array, common_values = {})
            if array
              array.map do |values|
                from_hash(api, values.merge(common_values))
              end
            end
          end

          def self.from_hash(api, attrs_or_struct)
            return nil unless attrs_or_struct

            if attrs_or_struct.respond_to?(:attributes=)
              # already a model
              obj = attrs_or_struct
            elsif obj = api.registry.find(self, attrs_or_struct['id'])
              obj.attributes = attrs_or_struct
            else
              obj = new(api, attrs_or_struct)
              api.registry.set(self, obj.id, obj)
            end
            obj
          end
        end
      end

      def initialize(api, attrs)
        self.api = api
        self.attributes = attrs
      end

      def attributes=(attrs)
        attrs.each do |key, val|
          setter = :"#{key}="
          if respond_to?(setter)
            send(setter, val)
          end
        end
      end

      def inspect
        %|#<#{self.class.name} #{(members - [:api]).map { |x| "#{x}=#{send(x).inspect}" }.join(" ")}>|
      end

      def <=>(other)
        unless other.is_a?(self.class)
          raise ArgumentError, "comparison of #{self.class.name} with #{other.class.name} failed"
        end
        sort_attributes <=> other.sort_attributes
      end

      def sort_attributes
        members.map { |m| sort_string(m.to_s) }
      end

      protected

      # Return ~, which comes late in lexical order, to avoid comparison to nil
      def sort_string(str)
        str || "~"
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
engineyard-cloud-client-2.1.1 lib/engineyard-cloud-client/models/api_struct.rb
engineyard-cloud-client-2.1.0 lib/engineyard-cloud-client/models/api_struct.rb
engineyard-cloud-client-1.0.16 lib/engineyard-cloud-client/models/api_struct.rb
engineyard-cloud-client-2.0.1 lib/engineyard-cloud-client/models/api_struct.rb
engineyard-cloud-client-2.0.0 lib/engineyard-cloud-client/models/api_struct.rb
engineyard-cloud-client-1.0.15 lib/engineyard-cloud-client/models/api_struct.rb
engineyard-cloud-client-1.0.14 lib/engineyard-cloud-client/models/api_struct.rb