Class: Redox::Model

Inherits:
Hashie::Trash
  • Object
show all
Includes:
Hashie::Extensions::Dash::Coercion, Hashie::Extensions::IgnoreUndeclared
Defined in:
lib/redox/model.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ Model

Returns a new instance of Model.



12
13
14
15
16
17
18
19
20
# File 'lib/redox/model.rb', line 12

def initialize(hash = {})
  if hash.keys.first.is_a? String
    hash = hash.transform_keys { |key|
      translated_key = self.class.translations[key.to_sym]
      translated_key.nil? ? key : translated_key
    }
  end
  super hash
end

Class Method Details

.from_redox_json(json) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/redox/model.rb', line 26

def self.from_redox_json(json)
  case json
  when String
    json = JSON.parse json
  end
  new json.transform_keys(&:to_sym)
end

.redox_property(redox_property, options = {}) ⇒ Object



22
23
24
# File 'lib/redox/model.rb', line 22

def self.redox_property(redox_property, options = {})
  property to_snake_case(redox_property).to_sym, options.merge({from: redox_property})
end

.to_snake_case(camel_cased_word) ⇒ String

Convert word from CamelCase to snake_case. This is roughly the same as the rails ‘String.underscore` method with the following simplications:

  • any word in all caps is assumed to be an acronym (ZIP -> zip)

  • only alphabetic characters are modified

Note: this function does not have an inverse. Both “Zip” and “ZIP” map to “zip”.

Parameters:

  • camel_cased_word (String)

    word to convert to snake case

Returns:

  • (String)

    camel_cased_qord converted to snake case



65
66
67
68
69
70
71
72
73
# File 'lib/redox/model.rb', line 65

def self.to_snake_case(camel_cased_word)
  word = camel_cased_word.to_s
  return word.downcase if word.upcase == word

  word.gsub!(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2')
  word.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
  word.downcase!
  word
end

Instance Method Details

#to_redox_hashObject



34
35
36
37
38
# File 'lib/redox/model.rb', line 34

def to_redox_hash
  to_h
    .transform_keys { |k| self.class.inverse_translations[k] }
    .transform_values { |v| value_to_redox_hash(v) }
end

#to_redox_jsonObject



50
51
52
# File 'lib/redox/model.rb', line 50

def to_redox_json
  to_redox_hash.to_json
end

#value_to_redox_hash(value) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'lib/redox/model.rb', line 40

def value_to_redox_hash(value)
  if value.respond_to?(:to_redox_hash)
    value.to_redox_hash
  elsif value.is_a?(Array)
    value.map { |element| value_to_redox_hash(element) }
  else
    value
  end
end