Last active
November 20, 2015 13:45
-
-
Save huyderman/eeff3d4ac30ec8ec2a51 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Class representing an Attribute Value Pair as used in SuperOffice | |
class AttributeValuePair | |
attr_reader :key | |
attr_reader :value | |
attr_reader :error | |
# @overload initialize(key:, value:, error: nil) | |
# Sets the key, value and optional error | |
# @param key [Object] | |
# @param value [Object] | |
# @param error [Object] | |
# @overload initialize(attribute_hash) | |
# Creates an AttributeValuePair from a hash | |
# @param attribute_hash [Hash] | |
# @example | |
# AttributeValuePair.new('foo' => 'bar', error: false) | |
# #=> #<AttributeValuePair key="foo", value="bar", error=false> | |
def initialize(key: nil, value: nil, error: nil, **hash) | |
@error = error | |
if hash.empty? | |
@key = key | |
@value = value | |
else | |
@key, @value = hash.to_a.first | |
end | |
end | |
# Returns an hash representation of the AttributeValuePair | |
# @example | |
# AttributeValuePair.new('foo' => 'bar').to_hash | |
# #=> { :key=>"foo", :value=>"bar", :error=>nil } | |
# @return [Hash] | |
def to_hash | |
{ key: @key, value: @value, error: @error } | |
end | |
# Returns the value of the AttributeValuePair as an hash | |
# @example | |
# AttributeValuePair.new('foo' => 'bar').to_h | |
# #=> { "foo" => "bar" } | |
# @return [Hash] | |
def to_h | |
{ @key => @value } | |
end | |
# Returns the value of the AttributeValuePair as an array | |
# @return [Array(Object,Object)] | |
def to_a | |
[@key, @value] | |
end | |
# @overload self.[](key, value, error=nil) | |
# @param key [Object] | |
# @param value [Object] | |
# @param error [Object] | |
# @return [AttributeValuePair] | |
# @example | |
# AttributeValuePair['foo', 'bar'] | |
# #=> #<AttributeValuePair key="foo", value="bar"> | |
# @overload self.[](value) | |
# @param value [Object] | |
# @return [AttributeValuePair] | |
# @example | |
# AttributeValuePair['foo'] | |
# #=> #<AttributeValuePair key="foo", value="foo"> | |
# @overload self.[](attribute_value_pair) | |
# @param attribute_value_pair [Hash] | |
# @return [AttributeValuePair] | |
# @example | |
# AttributeValuePair['foo' => 'bar'] | |
# #=> #<AttributeValuePair key="foo", value="bar"> | |
def self.[](*arr, **hsh) | |
case arr.length | |
when 0 | |
new(hsh) | |
when 1 | |
new(arr.first => arr.first) | |
when 2..3 | |
new(arr[0] => arr[1], error: arr[2]) | |
else | |
fail ArgumentError, "wrong number of arguments (#{arr.length} for 1..3)" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
good job