Module: CrystalApi::Attributes

Defined Under Namespace

Modules: ClassMethods Classes: NoRootElementDefined

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(receiver) ⇒ Object



95
96
97
98
99
100
# File 'lib/crystal_api/attributes.rb', line 95

def self.included(receiver)
  receiver.extend(ClassMethods)
  receiver.class_eval do
    @attributes = {}
  end
end

Instance Method Details

#==(other) ⇒ Object



102
103
104
# File 'lib/crystal_api/attributes.rb', line 102

def ==(other)
  self.eql?(other)
end

#as_json(options = {}) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
# File 'lib/crystal_api/attributes.rb', line 121

def as_json(options = {})
  {
    root_key => self.class.attributes.inject({}) { |acc, (key, _)|
      unless options.fetch(:except, []).include?(key.to_sym)
        value = send(key)
        acc[key.to_s] = value.respond_to?(:as_json) ? value.as_json : value
      end
      acc
    }
  }
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


106
107
108
109
110
111
# File 'lib/crystal_api/attributes.rb', line 106

def eql?(other)
  return false if other.class != self.class
  self.class.attributes.keys.all? do |field|
    self.send(field) == other.send(field)
  end
end

#hashObject



113
114
115
116
117
118
119
# File 'lib/crystal_api/attributes.rb', line 113

def hash
  result = 0
  self.class.attributes.keys.each do |field|
    result += self.send(field).hash
  end
  return result + self.class.hash
end

#initialize(args = {}) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/crystal_api/attributes.rb', line 77

def initialize(args = {})
  unexpected_keys = []

  args.each do |arg, value|
    if self.class.attributes.has_key?(arg.to_s)
      instance_variable_set("@#{arg}", parse_arg(arg, value))
    else
      unexpected_keys << arg
    end
  end

  if !unexpected_keys.empty?
    raise ArgumentError.new("Unexpected hash keys: #{unexpected_keys}")
  end

  self.freeze
end