Class: Pandoru::Models::PandoraModel

Inherits:
Object
  • Object
show all
Defined in:
lib/pandoru/models/_base.rb

Overview

PandoraModel base class similar to Python implementation

Direct Known Subclasses

PandoraListModel

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_client) ⇒ PandoraModel

Returns a new instance of PandoraModel.



180
181
182
# File 'lib/pandoru/models/_base.rb', line 180

def initialize(api_client)
  @api_client = api_client
end

Class Method Details

.date_field(name, json_key = nil) ⇒ Object



164
165
166
# File 'lib/pandoru/models/_base.rb', line 164

def self.date_field(name, json_key = nil)
  field(name, json_key, type: :date)
end

.field(name, json_key = nil, type: nil, &block) ⇒ Object



158
159
160
161
162
# File 'lib/pandoru/models/_base.rb', line 158

def self.field(name, json_key = nil, type: nil, &block)
  json_key ||= name.to_s
  fields[name] = { json_key: json_key, type: type, formatter: block }
  attr_accessor name
end

.fieldsObject



154
155
156
# File 'lib/pandoru/models/_base.rb', line 154

def self.fields
  @fields ||= {}
end

.from_json(api_client, data) ⇒ Object



168
169
170
171
172
173
# File 'lib/pandoru/models/_base.rb', line 168

def self.from_json(api_client, data)
  return nil unless data
  instance = new(api_client)
  instance.populate_from_json(data)
  instance
end

.from_json_list(api_client, data_list) ⇒ Object



175
176
177
178
# File 'lib/pandoru/models/_base.rb', line 175

def self.from_json_list(api_client, data_list)
  return [] unless data_list
  data_list.map { |data| from_json(api_client, data) }
end

Instance Method Details

#inspectObject



217
218
219
220
221
222
223
# File 'lib/pandoru/models/_base.rb', line 217

def inspect
  attrs = self.class.fields.keys.map do |name|
    value = instance_variable_get("@#{name}")
    "#{name}=#{value.inspect}"
  end.join(' ')
  "#<#{self.class.name} #{attrs}>"
end

#populate_from_json(data) ⇒ Object



184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/pandoru/models/_base.rb', line 184

def populate_from_json(data)
  self.class.fields.each do |name, config|
    json_key = config[:json_key]
    type = config[:type]
    formatter = config[:formatter]
    
    value = data[json_key]
    
    # Apply type conversion
    value = case type
            when :date
              parse_date(value)
            when :boolean
              parse_boolean(value)
            else
              value
            end
    
    # Apply custom formatter if provided
    value = formatter.call(value) if formatter && value
    
    instance_variable_set("@#{name}", value)
  end
end

#to_hObject



209
210
211
212
213
214
215
# File 'lib/pandoru/models/_base.rb', line 209

def to_h
  hash = {}
  self.class.fields.each do |name, _|
    hash[name] = instance_variable_get("@#{name}")
  end
  hash
end